crypto.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package crypto
  17. import (
  18. "crypto/ecdsa"
  19. "crypto/elliptic"
  20. "crypto/rand"
  21. "encoding/hex"
  22. "errors"
  23. "fmt"
  24. "io"
  25. "io/ioutil"
  26. "math/big"
  27. "os"
  28. "github.com/ethereum/go-ethereum/common"
  29. "github.com/ethereum/go-ethereum/common/math"
  30. "github.com/ethereum/go-ethereum/rlp"
  31. "golang.org/x/crypto/sha3"
  32. )
  33. //SignatureLength indicates the byte length required to carry a signature with recovery id.
  34. const SignatureLength = 64 + 1 // 64 bytes ECDSA signature + 1 byte recovery id
  35. // RecoveryIDOffset points to the byte offset within the signature that contains the recovery id.
  36. const RecoveryIDOffset = 64
  37. // DigestLength sets the signature digest exact length
  38. const DigestLength = 32
  39. var (
  40. secp256k1N, _ = new(big.Int).SetString("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", 16)
  41. secp256k1halfN = new(big.Int).Div(secp256k1N, big.NewInt(2))
  42. )
  43. var errInvalidPubkey = errors.New("invalid secp256k1 public key")
  44. // Keccak256 calculates and returns the Keccak256 hash of the input data.
  45. func Keccak256(data ...[]byte) []byte {
  46. d := sha3.NewLegacyKeccak256()
  47. for _, b := range data {
  48. d.Write(b)
  49. }
  50. return d.Sum(nil)
  51. }
  52. // Keccak256Hash calculates and returns the Keccak256 hash of the input data,
  53. // converting it to an internal Hash data structure.
  54. func Keccak256Hash(data ...[]byte) (h common.Hash) {
  55. d := sha3.NewLegacyKeccak256()
  56. for _, b := range data {
  57. d.Write(b)
  58. }
  59. d.Sum(h[:0])
  60. return h
  61. }
  62. // Keccak512 calculates and returns the Keccak512 hash of the input data.
  63. func Keccak512(data ...[]byte) []byte {
  64. d := sha3.NewLegacyKeccak512()
  65. for _, b := range data {
  66. d.Write(b)
  67. }
  68. return d.Sum(nil)
  69. }
  70. // CreateAddress creates an ethereum address given the bytes and the nonce
  71. func CreateAddress(b common.Address, nonce uint64) common.Address {
  72. data, _ := rlp.EncodeToBytes([]interface{}{b, nonce})
  73. return common.BytesToAddress(Keccak256(data)[12:])
  74. }
  75. // CreateAddress2 creates an ethereum address given the address bytes, initial
  76. // contract code hash and a salt.
  77. func CreateAddress2(b common.Address, salt [32]byte, inithash []byte) common.Address {
  78. return common.BytesToAddress(Keccak256([]byte{0xff}, b.Bytes(), salt[:], inithash)[12:])
  79. }
  80. // ToECDSA creates a private key with the given D value.
  81. func ToECDSA(d []byte) (*ecdsa.PrivateKey, error) {
  82. return toECDSA(d, true)
  83. }
  84. // ToECDSAUnsafe blindly converts a binary blob to a private key. It should almost
  85. // never be used unless you are sure the input is valid and want to avoid hitting
  86. // errors due to bad origin encoding (0 prefixes cut off).
  87. func ToECDSAUnsafe(d []byte) *ecdsa.PrivateKey {
  88. priv, _ := toECDSA(d, false)
  89. return priv
  90. }
  91. // toECDSA creates a private key with the given D value. The strict parameter
  92. // controls whether the key's length should be enforced at the curve size or
  93. // it can also accept legacy encodings (0 prefixes).
  94. func toECDSA(d []byte, strict bool) (*ecdsa.PrivateKey, error) {
  95. priv := new(ecdsa.PrivateKey)
  96. priv.PublicKey.Curve = S256()
  97. if strict && 8*len(d) != priv.Params().BitSize {
  98. return nil, fmt.Errorf("invalid length, need %d bits", priv.Params().BitSize)
  99. }
  100. priv.D = new(big.Int).SetBytes(d)
  101. // The priv.D must < N
  102. if priv.D.Cmp(secp256k1N) >= 0 {
  103. return nil, fmt.Errorf("invalid private key, >=N")
  104. }
  105. // The priv.D must not be zero or negative.
  106. if priv.D.Sign() <= 0 {
  107. return nil, fmt.Errorf("invalid private key, zero or negative")
  108. }
  109. priv.PublicKey.X, priv.PublicKey.Y = priv.PublicKey.Curve.ScalarBaseMult(d)
  110. if priv.PublicKey.X == nil {
  111. return nil, errors.New("invalid private key")
  112. }
  113. return priv, nil
  114. }
  115. // FromECDSA exports a private key into a binary dump.
  116. func FromECDSA(priv *ecdsa.PrivateKey) []byte {
  117. if priv == nil {
  118. return nil
  119. }
  120. return math.PaddedBigBytes(priv.D, priv.Params().BitSize/8)
  121. }
  122. // UnmarshalPubkey converts bytes to a secp256k1 public key.
  123. func UnmarshalPubkey(pub []byte) (*ecdsa.PublicKey, error) {
  124. x, y := elliptic.Unmarshal(S256(), pub)
  125. if x == nil {
  126. return nil, errInvalidPubkey
  127. }
  128. return &ecdsa.PublicKey{Curve: S256(), X: x, Y: y}, nil
  129. }
  130. func FromECDSAPub(pub *ecdsa.PublicKey) []byte {
  131. if pub == nil || pub.X == nil || pub.Y == nil {
  132. return nil
  133. }
  134. return elliptic.Marshal(S256(), pub.X, pub.Y)
  135. }
  136. // HexToECDSA parses a secp256k1 private key.
  137. func HexToECDSA(hexkey string) (*ecdsa.PrivateKey, error) {
  138. b, err := hex.DecodeString(hexkey)
  139. if err != nil {
  140. return nil, errors.New("invalid hex string")
  141. }
  142. return ToECDSA(b)
  143. }
  144. // LoadECDSA loads a secp256k1 private key from the given file.
  145. func LoadECDSA(file string) (*ecdsa.PrivateKey, error) {
  146. buf := make([]byte, 64)
  147. fd, err := os.Open(file)
  148. if err != nil {
  149. return nil, err
  150. }
  151. defer fd.Close()
  152. if _, err := io.ReadFull(fd, buf); err != nil {
  153. return nil, err
  154. }
  155. key, err := hex.DecodeString(string(buf))
  156. if err != nil {
  157. return nil, err
  158. }
  159. return ToECDSA(key)
  160. }
  161. // SaveECDSA saves a secp256k1 private key to the given file with
  162. // restrictive permissions. The key data is saved hex-encoded.
  163. func SaveECDSA(file string, key *ecdsa.PrivateKey) error {
  164. k := hex.EncodeToString(FromECDSA(key))
  165. return ioutil.WriteFile(file, []byte(k), 0600)
  166. }
  167. func GenerateKey() (*ecdsa.PrivateKey, error) {
  168. return ecdsa.GenerateKey(S256(), rand.Reader)
  169. }
  170. // ValidateSignatureValues verifies whether the signature values are valid with
  171. // the given chain rules. The v value is assumed to be either 0 or 1.
  172. func ValidateSignatureValues(v byte, r, s *big.Int, homestead bool) bool {
  173. if r.Cmp(common.Big1) < 0 || s.Cmp(common.Big1) < 0 {
  174. return false
  175. }
  176. // reject upper range of s values (ECDSA malleability)
  177. // see discussion in secp256k1/libsecp256k1/include/secp256k1.h
  178. if homestead && s.Cmp(secp256k1halfN) > 0 {
  179. return false
  180. }
  181. // Frontier: allow s to be in full N range
  182. return r.Cmp(secp256k1N) < 0 && s.Cmp(secp256k1N) < 0 && (v == 0 || v == 1)
  183. }
  184. func PubkeyToAddress(p ecdsa.PublicKey) common.Address {
  185. pubBytes := FromECDSAPub(&p)
  186. return common.BytesToAddress(Keccak256(pubBytes[1:])[12:])
  187. }
  188. func zeroBytes(bytes []byte) {
  189. for i := range bytes {
  190. bytes[i] = 0
  191. }
  192. }