crypto.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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. // Ecrecover returns the public key for the private key that was used to
  69. // calculate the signature.
  70. //
  71. // Note: secp256k1 expects the recover id to be either 0, 1. Ethereum
  72. // signatures have a recover id with an offset of 27. Callers must take
  73. // this into account and if "recovering" from an Ethereum signature adjust.
  74. func Ecrecover(hash, sig []byte) ([]byte, error) {
  75. return secp256k1.RecoverPubkey(hash, sig)
  76. }
  77. // New methods using proper ecdsa keys from the stdlib
  78. func ToECDSA(prv []byte) *ecdsa.PrivateKey {
  79. if len(prv) == 0 {
  80. return nil
  81. }
  82. priv := new(ecdsa.PrivateKey)
  83. priv.PublicKey.Curve = secp256k1.S256()
  84. priv.D = common.BigD(prv)
  85. priv.PublicKey.X, priv.PublicKey.Y = secp256k1.S256().ScalarBaseMult(prv)
  86. return priv
  87. }
  88. func FromECDSA(prv *ecdsa.PrivateKey) []byte {
  89. if prv == nil {
  90. return nil
  91. }
  92. return prv.D.Bytes()
  93. }
  94. func ToECDSAPub(pub []byte) *ecdsa.PublicKey {
  95. if len(pub) == 0 {
  96. return nil
  97. }
  98. x, y := elliptic.Unmarshal(secp256k1.S256(), pub)
  99. return &ecdsa.PublicKey{Curve: secp256k1.S256(), X: x, Y: y}
  100. }
  101. func FromECDSAPub(pub *ecdsa.PublicKey) []byte {
  102. if pub == nil || pub.X == nil || pub.Y == nil {
  103. return nil
  104. }
  105. return elliptic.Marshal(secp256k1.S256(), pub.X, pub.Y)
  106. }
  107. // HexToECDSA parses a secp256k1 private key.
  108. func HexToECDSA(hexkey string) (*ecdsa.PrivateKey, error) {
  109. b, err := hex.DecodeString(hexkey)
  110. if err != nil {
  111. return nil, errors.New("invalid hex string")
  112. }
  113. if len(b) != 32 {
  114. return nil, errors.New("invalid length, need 256 bits")
  115. }
  116. return ToECDSA(b), nil
  117. }
  118. // LoadECDSA loads a secp256k1 private key from the given file.
  119. // The key data is expected to be hex-encoded.
  120. func LoadECDSA(file string) (*ecdsa.PrivateKey, error) {
  121. buf := make([]byte, 64)
  122. fd, err := os.Open(file)
  123. if err != nil {
  124. return nil, err
  125. }
  126. defer fd.Close()
  127. if _, err := io.ReadFull(fd, buf); err != nil {
  128. return nil, err
  129. }
  130. key, err := hex.DecodeString(string(buf))
  131. if err != nil {
  132. return nil, err
  133. }
  134. return ToECDSA(key), nil
  135. }
  136. // SaveECDSA saves a secp256k1 private key to the given file with
  137. // restrictive permissions. The key data is saved hex-encoded.
  138. func SaveECDSA(file string, key *ecdsa.PrivateKey) error {
  139. k := hex.EncodeToString(FromECDSA(key))
  140. return ioutil.WriteFile(file, []byte(k), 0600)
  141. }
  142. func GenerateKey() (*ecdsa.PrivateKey, error) {
  143. return ecdsa.GenerateKey(secp256k1.S256(), rand.Reader)
  144. }
  145. // ValidateSignatureValues verifies whether the signature values are valid with
  146. // the given chain rules. The v value is assumed to be either 0 or 1.
  147. func ValidateSignatureValues(v byte, r, s *big.Int, homestead bool) bool {
  148. if r.Cmp(common.Big1) < 0 || s.Cmp(common.Big1) < 0 {
  149. return false
  150. }
  151. // reject upper range of s values (ECDSA malleability)
  152. // see discussion in secp256k1/libsecp256k1/include/secp256k1.h
  153. if homestead && s.Cmp(secp256k1.HalfN) > 0 {
  154. return false
  155. }
  156. // Frontier: allow s to be in full N range
  157. return r.Cmp(secp256k1.N) < 0 && s.Cmp(secp256k1.N) < 0 && (v == 0 || v == 1)
  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. // Sign calculates an ECDSA signature.
  168. //
  169. // This function is susceptible to chosen plaintext attacks that can leak
  170. // information about the private key that is used for signing. Callers must
  171. // be aware that the given hash cannot be chosen by an adversery. Common
  172. // solution is to hash any input before calculating the signature.
  173. //
  174. // The produced signature is in the [R || S || V] format where V is 0 or 1.
  175. func Sign(data []byte, prv *ecdsa.PrivateKey) (sig []byte, err error) {
  176. if len(data) != 32 {
  177. return nil, fmt.Errorf("hash is required to be exactly 32 bytes (%d)", len(data))
  178. }
  179. seckey := common.LeftPadBytes(prv.D.Bytes(), prv.Params().BitSize/8)
  180. defer zeroBytes(seckey)
  181. sig, err = secp256k1.Sign(data, seckey)
  182. return
  183. }
  184. func Encrypt(pub *ecdsa.PublicKey, message []byte) ([]byte, error) {
  185. return ecies.Encrypt(rand.Reader, ecies.ImportECDSAPublic(pub), message, nil, nil)
  186. }
  187. func Decrypt(prv *ecdsa.PrivateKey, ct []byte) ([]byte, error) {
  188. key := ecies.ImportECDSA(prv)
  189. return key.Decrypt(rand.Reader, ct, nil, nil)
  190. }
  191. func PubkeyToAddress(p ecdsa.PublicKey) common.Address {
  192. pubBytes := FromECDSAPub(&p)
  193. return common.BytesToAddress(Keccak256(pubBytes[1:])[12:])
  194. }
  195. func zeroBytes(bytes []byte) {
  196. for i := range bytes {
  197. bytes[i] = 0
  198. }
  199. }