crypto.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. "io"
  24. "io/ioutil"
  25. "math/big"
  26. "os"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/crypto/sha3"
  29. "github.com/ethereum/go-ethereum/rlp"
  30. )
  31. var (
  32. secp256k1_N, _ = new(big.Int).SetString("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", 16)
  33. secp256k1_halfN = new(big.Int).Div(secp256k1_N, big.NewInt(2))
  34. )
  35. // Hasher is a repetitive hasher allowing the same hash data structures to be
  36. // reused between hash runs instead of requiring new ones to be created.
  37. type Hasher func(data []byte) []byte
  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. // Keccak256Hasher creates a repetitive Keccak256 hasher, allowing the same hash
  57. // data structures to be reused between hash runs instead of requiring new ones
  58. // to be created.
  59. //
  60. // The returned function is not thread safe!
  61. func Keccak256Hasher() Hasher {
  62. hasher := sha3.NewKeccak256()
  63. return func(data []byte) []byte {
  64. hasher.Write(data)
  65. result := hasher.Sum(nil)
  66. hasher.Reset()
  67. return result
  68. }
  69. }
  70. // Keccak512 calculates and returns the Keccak512 hash of the input data.
  71. func Keccak512(data ...[]byte) []byte {
  72. d := sha3.NewKeccak512()
  73. for _, b := range data {
  74. d.Write(b)
  75. }
  76. return d.Sum(nil)
  77. }
  78. // Keccak512Hasher creates a repetitive Keccak512 hasher, allowing the same hash
  79. // data structures to be reused between hash runs instead of requiring new ones
  80. // to be created.
  81. //
  82. // The returned function is not thread safe!
  83. func Keccak512Hasher() Hasher {
  84. hasher := sha3.NewKeccak512()
  85. return func(data []byte) []byte {
  86. hasher.Write(data)
  87. result := hasher.Sum(nil)
  88. hasher.Reset()
  89. return result
  90. }
  91. }
  92. // Deprecated: For backward compatibility as other packages depend on these
  93. func Sha3Hash(data ...[]byte) common.Hash { return Keccak256Hash(data...) }
  94. // Creates an ethereum address given the bytes and the nonce
  95. func CreateAddress(b common.Address, nonce uint64) common.Address {
  96. data, _ := rlp.EncodeToBytes([]interface{}{b, nonce})
  97. return common.BytesToAddress(Keccak256(data)[12:])
  98. }
  99. // ToECDSA creates a private key with the given D value.
  100. func ToECDSA(prv []byte) *ecdsa.PrivateKey {
  101. if len(prv) == 0 {
  102. return nil
  103. }
  104. priv := new(ecdsa.PrivateKey)
  105. priv.PublicKey.Curve = S256()
  106. priv.D = new(big.Int).SetBytes(prv)
  107. priv.PublicKey.X, priv.PublicKey.Y = priv.PublicKey.Curve.ScalarBaseMult(prv)
  108. return priv
  109. }
  110. func FromECDSA(prv *ecdsa.PrivateKey) []byte {
  111. if prv == nil {
  112. return nil
  113. }
  114. return prv.D.Bytes()
  115. }
  116. func ToECDSAPub(pub []byte) *ecdsa.PublicKey {
  117. if len(pub) == 0 {
  118. return nil
  119. }
  120. x, y := elliptic.Unmarshal(S256(), pub)
  121. return &ecdsa.PublicKey{Curve: S256(), X: x, Y: y}
  122. }
  123. func FromECDSAPub(pub *ecdsa.PublicKey) []byte {
  124. if pub == nil || pub.X == nil || pub.Y == nil {
  125. return nil
  126. }
  127. return elliptic.Marshal(S256(), pub.X, pub.Y)
  128. }
  129. // HexToECDSA parses a secp256k1 private key.
  130. func HexToECDSA(hexkey string) (*ecdsa.PrivateKey, error) {
  131. b, err := hex.DecodeString(hexkey)
  132. if err != nil {
  133. return nil, errors.New("invalid hex string")
  134. }
  135. if len(b) != 32 {
  136. return nil, errors.New("invalid length, need 256 bits")
  137. }
  138. return ToECDSA(b), nil
  139. }
  140. // LoadECDSA loads a secp256k1 private key from the given file.
  141. // The key data is expected to be hex-encoded.
  142. func LoadECDSA(file string) (*ecdsa.PrivateKey, error) {
  143. buf := make([]byte, 64)
  144. fd, err := os.Open(file)
  145. if err != nil {
  146. return nil, err
  147. }
  148. defer fd.Close()
  149. if _, err := io.ReadFull(fd, buf); err != nil {
  150. return nil, err
  151. }
  152. key, err := hex.DecodeString(string(buf))
  153. if err != nil {
  154. return nil, err
  155. }
  156. return ToECDSA(key), nil
  157. }
  158. // SaveECDSA saves a secp256k1 private key to the given file with
  159. // restrictive permissions. The key data is saved hex-encoded.
  160. func SaveECDSA(file string, key *ecdsa.PrivateKey) error {
  161. k := hex.EncodeToString(FromECDSA(key))
  162. return ioutil.WriteFile(file, []byte(k), 0600)
  163. }
  164. func GenerateKey() (*ecdsa.PrivateKey, error) {
  165. return ecdsa.GenerateKey(S256(), rand.Reader)
  166. }
  167. // ValidateSignatureValues verifies whether the signature values are valid with
  168. // the given chain rules. The v value is assumed to be either 0 or 1.
  169. func ValidateSignatureValues(v byte, r, s *big.Int, homestead bool) bool {
  170. if r.Cmp(common.Big1) < 0 || s.Cmp(common.Big1) < 0 {
  171. return false
  172. }
  173. // reject upper range of s values (ECDSA malleability)
  174. // see discussion in secp256k1/libsecp256k1/include/secp256k1.h
  175. if homestead && s.Cmp(secp256k1_halfN) > 0 {
  176. return false
  177. }
  178. // Frontier: allow s to be in full N range
  179. return r.Cmp(secp256k1_N) < 0 && s.Cmp(secp256k1_N) < 0 && (v == 0 || v == 1)
  180. }
  181. func PubkeyToAddress(p ecdsa.PublicKey) common.Address {
  182. pubBytes := FromECDSAPub(&p)
  183. return common.BytesToAddress(Keccak256(pubBytes[1:])[12:])
  184. }
  185. func zeroBytes(bytes []byte) {
  186. for i := range bytes {
  187. bytes[i] = 0
  188. }
  189. }