crypto.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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. secp256k1_N, _ = new(big.Int).SetString("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", 16)
  35. secp256k1_halfN = new(big.Int).Div(secp256k1_N, big.NewInt(2))
  36. )
  37. // Keccak256 calculates and returns the Keccak256 hash of the input data.
  38. func Keccak256(data ...[]byte) []byte {
  39. d := sha3.NewKeccak256()
  40. for _, b := range data {
  41. d.Write(b)
  42. }
  43. return d.Sum(nil)
  44. }
  45. // Keccak256Hash calculates and returns the Keccak256 hash of the input data,
  46. // converting it to an internal Hash data structure.
  47. func Keccak256Hash(data ...[]byte) (h common.Hash) {
  48. d := sha3.NewKeccak256()
  49. for _, b := range data {
  50. d.Write(b)
  51. }
  52. d.Sum(h[:0])
  53. return h
  54. }
  55. // Keccak512 calculates and returns the Keccak512 hash of the input data.
  56. func Keccak512(data ...[]byte) []byte {
  57. d := sha3.NewKeccak512()
  58. for _, b := range data {
  59. d.Write(b)
  60. }
  61. return d.Sum(nil)
  62. }
  63. // Deprecated: For backward compatibility as other packages depend on these
  64. func Sha3Hash(data ...[]byte) common.Hash { return Keccak256Hash(data...) }
  65. // Creates an ethereum address given the bytes and the nonce
  66. func CreateAddress(b common.Address, nonce uint64) common.Address {
  67. data, _ := rlp.EncodeToBytes([]interface{}{b, nonce})
  68. return common.BytesToAddress(Keccak256(data)[12:])
  69. }
  70. // ToECDSA creates a private key with the given D value.
  71. func ToECDSA(d []byte) (*ecdsa.PrivateKey, error) {
  72. priv := new(ecdsa.PrivateKey)
  73. priv.PublicKey.Curve = S256()
  74. if 8*len(d) != priv.Params().BitSize {
  75. return nil, fmt.Errorf("invalid length, need %d bits", priv.Params().BitSize)
  76. }
  77. priv.D = new(big.Int).SetBytes(d)
  78. priv.PublicKey.X, priv.PublicKey.Y = priv.PublicKey.Curve.ScalarBaseMult(d)
  79. return priv, nil
  80. }
  81. func FromECDSA(prv *ecdsa.PrivateKey) []byte {
  82. if prv == nil {
  83. return nil
  84. }
  85. return math.PaddedBigBytes(prv.D, 32)
  86. }
  87. func ToECDSAPub(pub []byte) *ecdsa.PublicKey {
  88. if len(pub) == 0 {
  89. return nil
  90. }
  91. x, y := elliptic.Unmarshal(S256(), pub)
  92. return &ecdsa.PublicKey{Curve: S256(), X: x, Y: y}
  93. }
  94. func FromECDSAPub(pub *ecdsa.PublicKey) []byte {
  95. if pub == nil || pub.X == nil || pub.Y == nil {
  96. return nil
  97. }
  98. return elliptic.Marshal(S256(), pub.X, pub.Y)
  99. }
  100. // HexToECDSA parses a secp256k1 private key.
  101. func HexToECDSA(hexkey string) (*ecdsa.PrivateKey, error) {
  102. b, err := hex.DecodeString(hexkey)
  103. if err != nil {
  104. return nil, errors.New("invalid hex string")
  105. }
  106. return ToECDSA(b)
  107. }
  108. // LoadECDSA loads a secp256k1 private key from the given file.
  109. // The key data is expected to be hex-encoded.
  110. func LoadECDSA(file string) (*ecdsa.PrivateKey, error) {
  111. buf := make([]byte, 64)
  112. fd, err := os.Open(file)
  113. if err != nil {
  114. return nil, err
  115. }
  116. defer fd.Close()
  117. if _, err := io.ReadFull(fd, buf); err != nil {
  118. return nil, err
  119. }
  120. key, err := hex.DecodeString(string(buf))
  121. if err != nil {
  122. return nil, err
  123. }
  124. return ToECDSA(key)
  125. }
  126. // SaveECDSA saves a secp256k1 private key to the given file with
  127. // restrictive permissions. The key data is saved hex-encoded.
  128. func SaveECDSA(file string, key *ecdsa.PrivateKey) error {
  129. k := hex.EncodeToString(FromECDSA(key))
  130. return ioutil.WriteFile(file, []byte(k), 0600)
  131. }
  132. func GenerateKey() (*ecdsa.PrivateKey, error) {
  133. return ecdsa.GenerateKey(S256(), rand.Reader)
  134. }
  135. // ValidateSignatureValues verifies whether the signature values are valid with
  136. // the given chain rules. The v value is assumed to be either 0 or 1.
  137. func ValidateSignatureValues(v byte, r, s *big.Int, homestead bool) bool {
  138. if r.Cmp(common.Big1) < 0 || s.Cmp(common.Big1) < 0 {
  139. return false
  140. }
  141. // reject upper range of s values (ECDSA malleability)
  142. // see discussion in secp256k1/libsecp256k1/include/secp256k1.h
  143. if homestead && s.Cmp(secp256k1_halfN) > 0 {
  144. return false
  145. }
  146. // Frontier: allow s to be in full N range
  147. return r.Cmp(secp256k1_N) < 0 && s.Cmp(secp256k1_N) < 0 && (v == 0 || v == 1)
  148. }
  149. func PubkeyToAddress(p ecdsa.PublicKey) common.Address {
  150. pubBytes := FromECDSAPub(&p)
  151. return common.BytesToAddress(Keccak256(pubBytes[1:])[12:])
  152. }
  153. func zeroBytes(bytes []byte) {
  154. for i := range bytes {
  155. bytes[i] = 0
  156. }
  157. }