crypto.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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/crypto/sha3"
  31. "github.com/ethereum/go-ethereum/rlp"
  32. )
  33. var (
  34. secp256k1N, _ = new(big.Int).SetString("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", 16)
  35. secp256k1halfN = new(big.Int).Div(secp256k1N, big.NewInt(2))
  36. )
  37. var errInvalidPubkey = errors.New("invalid secp256k1 public key")
  38. // Keccak256 calculates and returns the Keccak256 hash of the input data.
  39. func Keccak256(data ...[]byte) []byte {
  40. d := sha3.NewKeccak256()
  41. for _, b := range data {
  42. d.Write(b)
  43. }
  44. return d.Sum(nil)
  45. }
  46. // Keccak256Hash calculates and returns the Keccak256 hash of the input data,
  47. // converting it to an internal Hash data structure.
  48. func Keccak256Hash(data ...[]byte) (h common.Hash) {
  49. d := sha3.NewKeccak256()
  50. for _, b := range data {
  51. d.Write(b)
  52. }
  53. d.Sum(h[:0])
  54. return h
  55. }
  56. // Keccak512 calculates and returns the Keccak512 hash of the input data.
  57. func Keccak512(data ...[]byte) []byte {
  58. d := sha3.NewKeccak512()
  59. for _, b := range data {
  60. d.Write(b)
  61. }
  62. return d.Sum(nil)
  63. }
  64. // CreateAddress creates an ethereum address given the bytes and the nonce
  65. func CreateAddress(b common.Address, nonce uint64) common.Address {
  66. data, _ := rlp.EncodeToBytes([]interface{}{b, nonce})
  67. return common.BytesToAddress(Keccak256(data)[12:])
  68. }
  69. // CreateAddress2 creates an ethereum address given the address bytes, initial
  70. // contract code hash and a salt.
  71. func CreateAddress2(b common.Address, salt [32]byte, inithash []byte) common.Address {
  72. return common.BytesToAddress(Keccak256([]byte{0xff}, b.Bytes(), salt[:], inithash)[12:])
  73. }
  74. // ToECDSA creates a private key with the given D value.
  75. func ToECDSA(d []byte) (*ecdsa.PrivateKey, error) {
  76. return toECDSA(d, true)
  77. }
  78. // ToECDSAUnsafe blindly converts a binary blob to a private key. It should almost
  79. // never be used unless you are sure the input is valid and want to avoid hitting
  80. // errors due to bad origin encoding (0 prefixes cut off).
  81. func ToECDSAUnsafe(d []byte) *ecdsa.PrivateKey {
  82. priv, _ := toECDSA(d, false)
  83. return priv
  84. }
  85. // toECDSA creates a private key with the given D value. The strict parameter
  86. // controls whether the key's length should be enforced at the curve size or
  87. // it can also accept legacy encodings (0 prefixes).
  88. func toECDSA(d []byte, strict bool) (*ecdsa.PrivateKey, error) {
  89. priv := new(ecdsa.PrivateKey)
  90. priv.PublicKey.Curve = S256()
  91. if strict && 8*len(d) != priv.Params().BitSize {
  92. return nil, fmt.Errorf("invalid length, need %d bits", priv.Params().BitSize)
  93. }
  94. priv.D = new(big.Int).SetBytes(d)
  95. // The priv.D must < N
  96. if priv.D.Cmp(secp256k1N) >= 0 {
  97. return nil, fmt.Errorf("invalid private key, >=N")
  98. }
  99. // The priv.D must not be zero or negative.
  100. if priv.D.Sign() <= 0 {
  101. return nil, fmt.Errorf("invalid private key, zero or negative")
  102. }
  103. priv.PublicKey.X, priv.PublicKey.Y = priv.PublicKey.Curve.ScalarBaseMult(d)
  104. if priv.PublicKey.X == nil {
  105. return nil, errors.New("invalid private key")
  106. }
  107. return priv, nil
  108. }
  109. // FromECDSA exports a private key into a binary dump.
  110. func FromECDSA(priv *ecdsa.PrivateKey) []byte {
  111. if priv == nil {
  112. return nil
  113. }
  114. return math.PaddedBigBytes(priv.D, priv.Params().BitSize/8)
  115. }
  116. // UnmarshalPubkey converts bytes to a secp256k1 public key.
  117. func UnmarshalPubkey(pub []byte) (*ecdsa.PublicKey, error) {
  118. x, y := elliptic.Unmarshal(S256(), pub)
  119. if x == nil {
  120. return nil, errInvalidPubkey
  121. }
  122. return &ecdsa.PublicKey{Curve: S256(), X: x, Y: y}, nil
  123. }
  124. func FromECDSAPub(pub *ecdsa.PublicKey) []byte {
  125. if pub == nil || pub.X == nil || pub.Y == nil {
  126. return nil
  127. }
  128. return elliptic.Marshal(S256(), pub.X, pub.Y)
  129. }
  130. // HexToECDSA parses a secp256k1 private key.
  131. func HexToECDSA(hexkey string) (*ecdsa.PrivateKey, error) {
  132. b, err := hex.DecodeString(hexkey)
  133. if err != nil {
  134. return nil, errors.New("invalid hex string")
  135. }
  136. return ToECDSA(b)
  137. }
  138. // LoadECDSA loads a secp256k1 private key from the given file.
  139. func LoadECDSA(file string) (*ecdsa.PrivateKey, error) {
  140. buf := make([]byte, 64)
  141. fd, err := os.Open(file)
  142. if err != nil {
  143. return nil, err
  144. }
  145. defer fd.Close()
  146. if _, err := io.ReadFull(fd, buf); err != nil {
  147. return nil, err
  148. }
  149. key, err := hex.DecodeString(string(buf))
  150. if err != nil {
  151. return nil, err
  152. }
  153. return ToECDSA(key)
  154. }
  155. // SaveECDSA saves a secp256k1 private key to the given file with
  156. // restrictive permissions. The key data is saved hex-encoded.
  157. func SaveECDSA(file string, key *ecdsa.PrivateKey) error {
  158. k := hex.EncodeToString(FromECDSA(key))
  159. return ioutil.WriteFile(file, []byte(k), 0600)
  160. }
  161. func GenerateKey() (*ecdsa.PrivateKey, error) {
  162. return ecdsa.GenerateKey(S256(), rand.Reader)
  163. }
  164. // ValidateSignatureValues verifies whether the signature values are valid with
  165. // the given chain rules. The v value is assumed to be either 0 or 1.
  166. func ValidateSignatureValues(v byte, r, s *big.Int, homestead bool) bool {
  167. if r.Cmp(common.Big1) < 0 || s.Cmp(common.Big1) < 0 {
  168. return false
  169. }
  170. // reject upper range of s values (ECDSA malleability)
  171. // see discussion in secp256k1/libsecp256k1/include/secp256k1.h
  172. if homestead && s.Cmp(secp256k1halfN) > 0 {
  173. return false
  174. }
  175. // Frontier: allow s to be in full N range
  176. return r.Cmp(secp256k1N) < 0 && s.Cmp(secp256k1N) < 0 && (v == 0 || v == 1)
  177. }
  178. func PubkeyToAddress(p ecdsa.PublicKey) common.Address {
  179. pubBytes := FromECDSAPub(&p)
  180. return common.BytesToAddress(Keccak256(pubBytes[1:])[12:])
  181. }
  182. func zeroBytes(bytes []byte) {
  183. for i := range bytes {
  184. bytes[i] = 0
  185. }
  186. }