crypto.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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. func ValidateSignatureValues(v byte, r, s *big.Int, homestead bool) bool {
  146. if r.Cmp(common.Big1) < 0 || s.Cmp(common.Big1) < 0 {
  147. return false
  148. }
  149. vint := uint32(v)
  150. // reject upper range of s values (ECDSA malleability)
  151. // see discussion in secp256k1/libsecp256k1/include/secp256k1.h
  152. if homestead && s.Cmp(secp256k1.HalfN) > 0 {
  153. return false
  154. }
  155. // Frontier: allow s to be in full N range
  156. if s.Cmp(secp256k1.N) >= 0 {
  157. return false
  158. }
  159. if r.Cmp(secp256k1.N) < 0 && (vint == 27 || vint == 28) {
  160. return true
  161. } else {
  162. return false
  163. }
  164. }
  165. func SigToPub(hash, sig []byte) (*ecdsa.PublicKey, error) {
  166. s, err := Ecrecover(hash, sig)
  167. if err != nil {
  168. return nil, err
  169. }
  170. x, y := elliptic.Unmarshal(secp256k1.S256(), s)
  171. return &ecdsa.PublicKey{Curve: secp256k1.S256(), X: x, Y: y}, nil
  172. }
  173. // Sign calculates an ECDSA signature.
  174. // This function is susceptible to choosen plaintext attacks that can leak
  175. // information about the private key that is used for signing. Callers must
  176. // be aware that the given hash cannot be choosen by an adversery. Common
  177. // solution is to hash any input before calculating the signature.
  178. //
  179. // Note: the calculated signature is not Ethereum compliant. The yellow paper
  180. // dictates Ethereum singature to have a V value with and offset of 27 v in [27,28].
  181. // Use SignEthereum to get an Ethereum compliant signature.
  182. func Sign(data []byte, prv *ecdsa.PrivateKey) (sig []byte, err error) {
  183. if len(data) != 32 {
  184. return nil, fmt.Errorf("hash is required to be exactly 32 bytes (%d)", len(data))
  185. }
  186. seckey := common.LeftPadBytes(prv.D.Bytes(), prv.Params().BitSize/8)
  187. defer zeroBytes(seckey)
  188. sig, err = secp256k1.Sign(data, seckey)
  189. return
  190. }
  191. // SignEthereum calculates an Ethereum ECDSA signature.
  192. // This function is susceptible to choosen plaintext attacks that can leak
  193. // information about the private key that is used for signing. Callers must
  194. // be aware that the given hash cannot be freely choosen by an adversery.
  195. // Common solution is to hash the message before calculating the signature.
  196. func SignEthereum(data []byte, prv *ecdsa.PrivateKey) ([]byte, error) {
  197. sig, err := Sign(data, prv)
  198. if err != nil {
  199. return nil, err
  200. }
  201. sig[64] += 27 // as described in the yellow paper
  202. return sig, err
  203. }
  204. func Encrypt(pub *ecdsa.PublicKey, message []byte) ([]byte, error) {
  205. return ecies.Encrypt(rand.Reader, ecies.ImportECDSAPublic(pub), message, nil, nil)
  206. }
  207. func Decrypt(prv *ecdsa.PrivateKey, ct []byte) ([]byte, error) {
  208. key := ecies.ImportECDSA(prv)
  209. return key.Decrypt(rand.Reader, ct, nil, nil)
  210. }
  211. func PubkeyToAddress(p ecdsa.PublicKey) common.Address {
  212. pubBytes := FromECDSAPub(&p)
  213. return common.BytesToAddress(Keccak256(pubBytes[1:])[12:])
  214. }
  215. func zeroBytes(bytes []byte) {
  216. for i := range bytes {
  217. bytes[i] = 0
  218. }
  219. }