crypto.go 4.6 KB

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