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.

173 lines
4.8 KiB

  1. package secp256k1
  2. import (
  3. "bytes"
  4. "crypto/sha256"
  5. "crypto/subtle"
  6. "fmt"
  7. "io"
  8. "math/big"
  9. secp256k1 "github.com/btcsuite/btcd/btcec"
  10. "golang.org/x/crypto/ripemd160" // nolint: staticcheck // necessary for Bitcoin address format
  11. "github.com/tendermint/tendermint/crypto"
  12. tmjson "github.com/tendermint/tendermint/libs/json"
  13. )
  14. //-------------------------------------
  15. const (
  16. PrivKeyName = "tendermint/PrivKeySecp256k1"
  17. PubKeyName = "tendermint/PubKeySecp256k1"
  18. KeyType = "secp256k1"
  19. PrivKeySize = 32
  20. )
  21. func init() {
  22. tmjson.RegisterType(PubKey{}, PubKeyName)
  23. tmjson.RegisterType(PrivKey{}, PrivKeyName)
  24. }
  25. var _ crypto.PrivKey = PrivKey{}
  26. // PrivKey implements PrivKey.
  27. type PrivKey []byte
  28. // Bytes marshalls the private key using amino encoding.
  29. func (privKey PrivKey) Bytes() []byte {
  30. return []byte(privKey)
  31. }
  32. // PubKey performs the point-scalar multiplication from the privKey on the
  33. // generator point to get the pubkey.
  34. func (privKey PrivKey) PubKey() crypto.PubKey {
  35. _, pubkeyObject := secp256k1.PrivKeyFromBytes(secp256k1.S256(), privKey)
  36. pk := pubkeyObject.SerializeCompressed()
  37. return PubKey(pk)
  38. }
  39. // Equals - you probably don't need to use this.
  40. // Runs in constant time based on length of the keys.
  41. func (privKey PrivKey) Equals(other crypto.PrivKey) bool {
  42. if otherSecp, ok := other.(PrivKey); ok {
  43. return subtle.ConstantTimeCompare(privKey[:], otherSecp[:]) == 1
  44. }
  45. return false
  46. }
  47. func (privKey PrivKey) Type() string {
  48. return KeyType
  49. }
  50. // GenPrivKey generates a new ECDSA private key on curve secp256k1 private key.
  51. // It uses OS randomness to generate the private key.
  52. func GenPrivKey() PrivKey {
  53. return genPrivKey(crypto.CReader())
  54. }
  55. // genPrivKey generates a new secp256k1 private key using the provided reader.
  56. func genPrivKey(rand io.Reader) PrivKey {
  57. var privKeyBytes [PrivKeySize]byte
  58. d := new(big.Int)
  59. for {
  60. privKeyBytes = [PrivKeySize]byte{}
  61. _, err := io.ReadFull(rand, privKeyBytes[:])
  62. if err != nil {
  63. panic(err)
  64. }
  65. d.SetBytes(privKeyBytes[:])
  66. // break if we found a valid point (i.e. > 0 and < N == curverOrder)
  67. isValidFieldElement := 0 < d.Sign() && d.Cmp(secp256k1.S256().N) < 0
  68. if isValidFieldElement {
  69. break
  70. }
  71. }
  72. return PrivKey(privKeyBytes[:])
  73. }
  74. var one = new(big.Int).SetInt64(1)
  75. // GenPrivKeySecp256k1 hashes the secret with SHA2, and uses
  76. // that 32 byte output to create the private key.
  77. //
  78. // It makes sure the private key is a valid field element by setting:
  79. //
  80. // c = sha256(secret)
  81. // k = (c mod (n − 1)) + 1, where n = curve order.
  82. //
  83. // NOTE: secret should be the output of a KDF like bcrypt,
  84. // if it's derived from user input.
  85. func GenPrivKeySecp256k1(secret []byte) PrivKey {
  86. secHash := sha256.Sum256(secret)
  87. // to guarantee that we have a valid field element, we use the approach of:
  88. // "Suite B Implementer’s Guide to FIPS 186-3", A.2.1
  89. // https://apps.nsa.gov/iaarchive/library/ia-guidance/ia-solutions-for-classified/algorithm-guidance/suite-b-implementers-guide-to-fips-186-3-ecdsa.cfm
  90. // see also https://github.com/golang/go/blob/0380c9ad38843d523d9c9804fe300cb7edd7cd3c/src/crypto/ecdsa/ecdsa.go#L89-L101
  91. fe := new(big.Int).SetBytes(secHash[:])
  92. n := new(big.Int).Sub(secp256k1.S256().N, one)
  93. fe.Mod(fe, n)
  94. fe.Add(fe, one)
  95. feB := fe.Bytes()
  96. privKey32 := make([]byte, PrivKeySize)
  97. // copy feB over to fixed 32 byte privKey32 and pad (if necessary)
  98. copy(privKey32[32-len(feB):32], feB)
  99. return PrivKey(privKey32)
  100. }
  101. //-------------------------------------
  102. var _ crypto.PubKey = PubKey{}
  103. // PubKeySize is comprised of 32 bytes for one field element
  104. // (the x-coordinate), plus one byte for the parity of the y-coordinate.
  105. const PubKeySize = 33
  106. // PubKey implements crypto.PubKey.
  107. // It is the compressed form of the pubkey. The first byte depends is a 0x02 byte
  108. // if the y-coordinate is the lexicographically largest of the two associated with
  109. // the x-coordinate. Otherwise the first byte is a 0x03.
  110. // This prefix is followed with the x-coordinate.
  111. type PubKey []byte
  112. // Address returns a Bitcoin style addresses: RIPEMD160(SHA256(pubkey))
  113. func (pubKey PubKey) Address() crypto.Address {
  114. if len(pubKey) != PubKeySize {
  115. panic("length of pubkey is incorrect")
  116. }
  117. hasherSHA256 := sha256.New()
  118. _, _ = hasherSHA256.Write(pubKey) // does not error
  119. sha := hasherSHA256.Sum(nil)
  120. hasherRIPEMD160 := ripemd160.New()
  121. _, _ = hasherRIPEMD160.Write(sha) // does not error
  122. return crypto.Address(hasherRIPEMD160.Sum(nil))
  123. }
  124. // Bytes returns the pubkey marshalled with amino encoding.
  125. func (pubKey PubKey) Bytes() []byte {
  126. return []byte(pubKey)
  127. }
  128. func (pubKey PubKey) String() string {
  129. return fmt.Sprintf("PubKeySecp256k1{%X}", pubKey[:])
  130. }
  131. func (pubKey PubKey) Equals(other crypto.PubKey) bool {
  132. if otherSecp, ok := other.(PubKey); ok {
  133. return bytes.Equal(pubKey[:], otherSecp[:])
  134. }
  135. return false
  136. }
  137. func (pubKey PubKey) Type() string {
  138. return KeyType
  139. }