crypto.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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. "crypto/sha256"
  22. "fmt"
  23. "io"
  24. "io/ioutil"
  25. "math/big"
  26. "os"
  27. "encoding/hex"
  28. "errors"
  29. "github.com/ethereum/go-ethereum/common"
  30. "github.com/ethereum/go-ethereum/crypto/ecies"
  31. "github.com/ethereum/go-ethereum/crypto/secp256k1"
  32. "github.com/ethereum/go-ethereum/crypto/sha3"
  33. "github.com/ethereum/go-ethereum/rlp"
  34. "golang.org/x/crypto/ripemd160"
  35. )
  36. func Keccak256(data ...[]byte) []byte {
  37. d := sha3.NewKeccak256()
  38. for _, b := range data {
  39. d.Write(b)
  40. }
  41. return d.Sum(nil)
  42. }
  43. func Keccak256Hash(data ...[]byte) (h common.Hash) {
  44. d := sha3.NewKeccak256()
  45. for _, b := range data {
  46. d.Write(b)
  47. }
  48. d.Sum(h[:0])
  49. return h
  50. }
  51. // Deprecated: For backward compatibility as other packages depend on these
  52. func Sha3(data ...[]byte) []byte { return Keccak256(data...) }
  53. func Sha3Hash(data ...[]byte) common.Hash { return Keccak256Hash(data...) }
  54. // Creates an ethereum address given the bytes and the nonce
  55. func CreateAddress(b common.Address, nonce uint64) common.Address {
  56. data, _ := rlp.EncodeToBytes([]interface{}{b, nonce})
  57. return common.BytesToAddress(Keccak256(data)[12:])
  58. }
  59. func Sha256(data []byte) []byte {
  60. hash := sha256.Sum256(data)
  61. return hash[:]
  62. }
  63. func Ripemd160(data []byte) []byte {
  64. ripemd := ripemd160.New()
  65. ripemd.Write(data)
  66. return ripemd.Sum(nil)
  67. }
  68. func Ecrecover(hash, sig []byte) ([]byte, error) {
  69. return secp256k1.RecoverPubkey(hash, sig)
  70. }
  71. // New methods using proper ecdsa keys from the stdlib
  72. func ToECDSA(prv []byte) *ecdsa.PrivateKey {
  73. if len(prv) == 0 {
  74. return nil
  75. }
  76. priv := new(ecdsa.PrivateKey)
  77. priv.PublicKey.Curve = secp256k1.S256()
  78. priv.D = common.BigD(prv)
  79. priv.PublicKey.X, priv.PublicKey.Y = secp256k1.S256().ScalarBaseMult(prv)
  80. return priv
  81. }
  82. func FromECDSA(prv *ecdsa.PrivateKey) []byte {
  83. if prv == nil {
  84. return nil
  85. }
  86. return prv.D.Bytes()
  87. }
  88. func ToECDSAPub(pub []byte) *ecdsa.PublicKey {
  89. if len(pub) == 0 {
  90. return nil
  91. }
  92. x, y := elliptic.Unmarshal(secp256k1.S256(), pub)
  93. return &ecdsa.PublicKey{Curve: secp256k1.S256(), X: x, Y: y}
  94. }
  95. func FromECDSAPub(pub *ecdsa.PublicKey) []byte {
  96. if pub == nil || pub.X == nil || pub.Y == nil {
  97. return nil
  98. }
  99. return elliptic.Marshal(secp256k1.S256(), pub.X, pub.Y)
  100. }
  101. // HexToECDSA parses a secp256k1 private key.
  102. func HexToECDSA(hexkey string) (*ecdsa.PrivateKey, error) {
  103. b, err := hex.DecodeString(hexkey)
  104. if err != nil {
  105. return nil, errors.New("invalid hex string")
  106. }
  107. if len(b) != 32 {
  108. return nil, errors.New("invalid length, need 256 bits")
  109. }
  110. return ToECDSA(b), nil
  111. }
  112. // LoadECDSA loads a secp256k1 private key from the given file.
  113. // The key data is expected to be hex-encoded.
  114. func LoadECDSA(file string) (*ecdsa.PrivateKey, error) {
  115. buf := make([]byte, 64)
  116. fd, err := os.Open(file)
  117. if err != nil {
  118. return nil, err
  119. }
  120. defer fd.Close()
  121. if _, err := io.ReadFull(fd, buf); err != nil {
  122. return nil, err
  123. }
  124. key, err := hex.DecodeString(string(buf))
  125. if err != nil {
  126. return nil, err
  127. }
  128. return ToECDSA(key), nil
  129. }
  130. // SaveECDSA saves a secp256k1 private key to the given file with
  131. // restrictive permissions. The key data is saved hex-encoded.
  132. func SaveECDSA(file string, key *ecdsa.PrivateKey) error {
  133. k := hex.EncodeToString(FromECDSA(key))
  134. return ioutil.WriteFile(file, []byte(k), 0600)
  135. }
  136. func GenerateKey() (*ecdsa.PrivateKey, error) {
  137. return ecdsa.GenerateKey(secp256k1.S256(), rand.Reader)
  138. }
  139. func ValidateSignatureValues(v byte, r, s *big.Int, homestead bool) bool {
  140. if r.Cmp(common.Big1) < 0 || s.Cmp(common.Big1) < 0 {
  141. return false
  142. }
  143. vint := uint32(v)
  144. // reject upper range of s values (ECDSA malleability)
  145. // see discussion in secp256k1/libsecp256k1/include/secp256k1.h
  146. if homestead && s.Cmp(secp256k1.HalfN) > 0 {
  147. return false
  148. }
  149. // Frontier: allow s to be in full N range
  150. if s.Cmp(secp256k1.N) >= 0 {
  151. return false
  152. }
  153. if r.Cmp(secp256k1.N) < 0 && (vint == 27 || vint == 28) {
  154. return true
  155. } else {
  156. return false
  157. }
  158. }
  159. func SigToPub(hash, sig []byte) (*ecdsa.PublicKey, error) {
  160. s, err := Ecrecover(hash, sig)
  161. if err != nil {
  162. return nil, err
  163. }
  164. x, y := elliptic.Unmarshal(secp256k1.S256(), s)
  165. return &ecdsa.PublicKey{Curve: secp256k1.S256(), X: x, Y: y}, nil
  166. }
  167. func Sign(hash []byte, prv *ecdsa.PrivateKey) (sig []byte, err error) {
  168. if len(hash) != 32 {
  169. return nil, fmt.Errorf("hash is required to be exactly 32 bytes (%d)", len(hash))
  170. }
  171. seckey := common.LeftPadBytes(prv.D.Bytes(), prv.Params().BitSize/8)
  172. defer zeroBytes(seckey)
  173. sig, err = secp256k1.Sign(hash, seckey)
  174. return
  175. }
  176. func Encrypt(pub *ecdsa.PublicKey, message []byte) ([]byte, error) {
  177. return ecies.Encrypt(rand.Reader, ecies.ImportECDSAPublic(pub), message, nil, nil)
  178. }
  179. func Decrypt(prv *ecdsa.PrivateKey, ct []byte) ([]byte, error) {
  180. key := ecies.ImportECDSA(prv)
  181. return key.Decrypt(rand.Reader, ct, nil, nil)
  182. }
  183. func PubkeyToAddress(p ecdsa.PublicKey) common.Address {
  184. pubBytes := FromECDSAPub(&p)
  185. return common.BytesToAddress(Keccak256(pubBytes[1:])[12:])
  186. }
  187. func zeroBytes(bytes []byte) {
  188. for i := range bytes {
  189. bytes[i] = 0
  190. }
  191. }