You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

90 lines
2.3 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. package crypto
  2. import (
  3. "github.com/tendermint/ed25519"
  4. "github.com/tendermint/ed25519/extra25519"
  5. . "github.com/tendermint/go-common"
  6. "github.com/tendermint/go-wire"
  7. )
  8. // PrivKey is part of PrivAccount and state.PrivValidator.
  9. type PrivKey interface {
  10. Bytes() []byte
  11. Sign(msg []byte) Signature
  12. PubKey() PubKey
  13. }
  14. // Types of PrivKey implementations
  15. const (
  16. PrivKeyTypeEd25519 = byte(0x01)
  17. )
  18. // for wire.readReflect
  19. var _ = wire.RegisterInterface(
  20. struct{ PrivKey }{},
  21. wire.ConcreteType{PrivKeyEd25519{}, PrivKeyTypeEd25519},
  22. )
  23. func PrivKeyFromBytes(privKeyBytes []byte) (privKey PrivKey, err error) {
  24. err = wire.ReadBinaryBytes(privKeyBytes, &privKey)
  25. return
  26. }
  27. //-------------------------------------
  28. // Implements PrivKey
  29. type PrivKeyEd25519 [64]byte
  30. func (privKey PrivKeyEd25519) Bytes() []byte {
  31. return wire.BinaryBytes(struct{ PrivKey }{privKey})
  32. }
  33. func (key PrivKeyEd25519) Sign(msg []byte) Signature {
  34. privKeyBytes := [64]byte(key)
  35. signatureBytes := ed25519.Sign(&privKeyBytes, msg)
  36. return SignatureEd25519(*signatureBytes)
  37. }
  38. func (privKey PrivKeyEd25519) PubKey() PubKey {
  39. privKeyBytes := [64]byte(privKey)
  40. return PubKeyEd25519(*ed25519.MakePublicKey(&privKeyBytes))
  41. }
  42. func (privKey PrivKeyEd25519) ToCurve25519() *[32]byte {
  43. keyCurve25519 := new([32]byte)
  44. privKeyBytes := [64]byte(privKey)
  45. extra25519.PrivateKeyToCurve25519(keyCurve25519, &privKeyBytes)
  46. return keyCurve25519
  47. }
  48. func (privKey PrivKeyEd25519) String() string {
  49. return Fmt("PrivKeyEd25519{*****}")
  50. }
  51. // Deterministically generates new priv-key bytes from key.
  52. func (key PrivKeyEd25519) Generate(index int) PrivKeyEd25519 {
  53. newBytes := wire.BinarySha256(struct {
  54. PrivKey [64]byte
  55. Index int
  56. }{key, index})
  57. var newKey [64]byte
  58. copy(newKey[:], newBytes)
  59. return PrivKeyEd25519(newKey)
  60. }
  61. func GenPrivKeyEd25519() PrivKeyEd25519 {
  62. privKeyBytes := new([64]byte)
  63. copy(privKeyBytes[:32], CRandBytes(32))
  64. ed25519.MakePublicKey(privKeyBytes)
  65. return PrivKeyEd25519(*privKeyBytes)
  66. }
  67. // NOTE: secret should be the output of a KDF like bcrypt,
  68. // if it's derived from user input.
  69. func GenPrivKeyEd25519FromSecret(secret []byte) PrivKeyEd25519 {
  70. privKey32 := Sha256(secret) // Not Ripemd160 because we want 32 bytes.
  71. privKeyBytes := new([64]byte)
  72. copy(privKeyBytes[:32], privKey32)
  73. ed25519.MakePublicKey(privKeyBytes)
  74. return PrivKeyEd25519(*privKeyBytes)
  75. }