crypto.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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. "bufio"
  19. "crypto/ecdsa"
  20. "crypto/elliptic"
  21. "crypto/rand"
  22. "encoding/hex"
  23. "errors"
  24. "fmt"
  25. "hash"
  26. "io"
  27. "io/ioutil"
  28. "math/big"
  29. "os"
  30. "github.com/ethereum/go-ethereum/common"
  31. "github.com/ethereum/go-ethereum/common/math"
  32. "github.com/ethereum/go-ethereum/rlp"
  33. "golang.org/x/crypto/sha3"
  34. )
  35. //SignatureLength indicates the byte length required to carry a signature with recovery id.
  36. const SignatureLength = 64 + 1 // 64 bytes ECDSA signature + 1 byte recovery id
  37. // RecoveryIDOffset points to the byte offset within the signature that contains the recovery id.
  38. const RecoveryIDOffset = 64
  39. // DigestLength sets the signature digest exact length
  40. const DigestLength = 32
  41. var (
  42. secp256k1N, _ = new(big.Int).SetString("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", 16)
  43. secp256k1halfN = new(big.Int).Div(secp256k1N, big.NewInt(2))
  44. )
  45. var errInvalidPubkey = errors.New("invalid secp256k1 public key")
  46. // KeccakState wraps sha3.state. In addition to the usual hash methods, it also supports
  47. // Read to get a variable amount of data from the hash state. Read is faster than Sum
  48. // because it doesn't copy the internal state, but also modifies the internal state.
  49. type KeccakState interface {
  50. hash.Hash
  51. Read([]byte) (int, error)
  52. }
  53. // Keccak256 calculates and returns the Keccak256 hash of the input data.
  54. func Keccak256(data ...[]byte) []byte {
  55. b := make([]byte, 32)
  56. d := sha3.NewLegacyKeccak256().(KeccakState)
  57. for _, b := range data {
  58. d.Write(b)
  59. }
  60. d.Read(b)
  61. return b
  62. }
  63. // Keccak256Hash calculates and returns the Keccak256 hash of the input data,
  64. // converting it to an internal Hash data structure.
  65. func Keccak256Hash(data ...[]byte) (h common.Hash) {
  66. d := sha3.NewLegacyKeccak256().(KeccakState)
  67. for _, b := range data {
  68. d.Write(b)
  69. }
  70. d.Read(h[:])
  71. return h
  72. }
  73. // Keccak512 calculates and returns the Keccak512 hash of the input data.
  74. func Keccak512(data ...[]byte) []byte {
  75. d := sha3.NewLegacyKeccak512()
  76. for _, b := range data {
  77. d.Write(b)
  78. }
  79. return d.Sum(nil)
  80. }
  81. // CreateAddress creates an ethereum address given the bytes and the nonce
  82. func CreateAddress(b common.Address, nonce uint64) common.Address {
  83. data, _ := rlp.EncodeToBytes([]interface{}{b, nonce})
  84. return common.BytesToAddress(Keccak256(data)[12:])
  85. }
  86. // CreateAddress2 creates an ethereum address given the address bytes, initial
  87. // contract code hash and a salt.
  88. func CreateAddress2(b common.Address, salt [32]byte, inithash []byte) common.Address {
  89. return common.BytesToAddress(Keccak256([]byte{0xff}, b.Bytes(), salt[:], inithash)[12:])
  90. }
  91. // ToECDSA creates a private key with the given D value.
  92. func ToECDSA(d []byte) (*ecdsa.PrivateKey, error) {
  93. return toECDSA(d, true)
  94. }
  95. // ToECDSAUnsafe blindly converts a binary blob to a private key. It should almost
  96. // never be used unless you are sure the input is valid and want to avoid hitting
  97. // errors due to bad origin encoding (0 prefixes cut off).
  98. func ToECDSAUnsafe(d []byte) *ecdsa.PrivateKey {
  99. priv, _ := toECDSA(d, false)
  100. return priv
  101. }
  102. // toECDSA creates a private key with the given D value. The strict parameter
  103. // controls whether the key's length should be enforced at the curve size or
  104. // it can also accept legacy encodings (0 prefixes).
  105. func toECDSA(d []byte, strict bool) (*ecdsa.PrivateKey, error) {
  106. priv := new(ecdsa.PrivateKey)
  107. priv.PublicKey.Curve = S256()
  108. if strict && 8*len(d) != priv.Params().BitSize {
  109. return nil, fmt.Errorf("invalid length, need %d bits", priv.Params().BitSize)
  110. }
  111. priv.D = new(big.Int).SetBytes(d)
  112. // The priv.D must < N
  113. if priv.D.Cmp(secp256k1N) >= 0 {
  114. return nil, fmt.Errorf("invalid private key, >=N")
  115. }
  116. // The priv.D must not be zero or negative.
  117. if priv.D.Sign() <= 0 {
  118. return nil, fmt.Errorf("invalid private key, zero or negative")
  119. }
  120. priv.PublicKey.X, priv.PublicKey.Y = priv.PublicKey.Curve.ScalarBaseMult(d)
  121. if priv.PublicKey.X == nil {
  122. return nil, errors.New("invalid private key")
  123. }
  124. return priv, nil
  125. }
  126. // FromECDSA exports a private key into a binary dump.
  127. func FromECDSA(priv *ecdsa.PrivateKey) []byte {
  128. if priv == nil {
  129. return nil
  130. }
  131. return math.PaddedBigBytes(priv.D, priv.Params().BitSize/8)
  132. }
  133. // UnmarshalPubkey converts bytes to a secp256k1 public key.
  134. func UnmarshalPubkey(pub []byte) (*ecdsa.PublicKey, error) {
  135. x, y := elliptic.Unmarshal(S256(), pub)
  136. if x == nil {
  137. return nil, errInvalidPubkey
  138. }
  139. return &ecdsa.PublicKey{Curve: S256(), X: x, Y: y}, nil
  140. }
  141. func FromECDSAPub(pub *ecdsa.PublicKey) []byte {
  142. if pub == nil || pub.X == nil || pub.Y == nil {
  143. return nil
  144. }
  145. return elliptic.Marshal(S256(), pub.X, pub.Y)
  146. }
  147. // HexToECDSA parses a secp256k1 private key.
  148. func HexToECDSA(hexkey string) (*ecdsa.PrivateKey, error) {
  149. b, err := hex.DecodeString(hexkey)
  150. if byteErr, ok := err.(hex.InvalidByteError); ok {
  151. return nil, fmt.Errorf("invalid hex character %q in private key", byte(byteErr))
  152. } else if err != nil {
  153. return nil, errors.New("invalid hex data for private key")
  154. }
  155. return ToECDSA(b)
  156. }
  157. // LoadECDSA loads a secp256k1 private key from the given file.
  158. func LoadECDSA(file string) (*ecdsa.PrivateKey, error) {
  159. fd, err := os.Open(file)
  160. if err != nil {
  161. return nil, err
  162. }
  163. defer fd.Close()
  164. r := bufio.NewReader(fd)
  165. buf := make([]byte, 64)
  166. n, err := readASCII(buf, r)
  167. if err != nil {
  168. return nil, err
  169. } else if n != len(buf) {
  170. return nil, fmt.Errorf("key file too short, want 64 hex characters")
  171. }
  172. if err := checkKeyFileEnd(r); err != nil {
  173. return nil, err
  174. }
  175. return HexToECDSA(string(buf))
  176. }
  177. // readASCII reads into 'buf', stopping when the buffer is full or
  178. // when a non-printable control character is encountered.
  179. func readASCII(buf []byte, r *bufio.Reader) (n int, err error) {
  180. for ; n < len(buf); n++ {
  181. buf[n], err = r.ReadByte()
  182. switch {
  183. case err == io.EOF || buf[n] < '!':
  184. return n, nil
  185. case err != nil:
  186. return n, err
  187. }
  188. }
  189. return n, nil
  190. }
  191. // checkKeyFileEnd skips over additional newlines at the end of a key file.
  192. func checkKeyFileEnd(r *bufio.Reader) error {
  193. for i := 0; ; i++ {
  194. b, err := r.ReadByte()
  195. switch {
  196. case err == io.EOF:
  197. return nil
  198. case err != nil:
  199. return err
  200. case b != '\n' && b != '\r':
  201. return fmt.Errorf("invalid character %q at end of key file", b)
  202. case i >= 2:
  203. return errors.New("key file too long, want 64 hex characters")
  204. }
  205. }
  206. }
  207. // SaveECDSA saves a secp256k1 private key to the given file with
  208. // restrictive permissions. The key data is saved hex-encoded.
  209. func SaveECDSA(file string, key *ecdsa.PrivateKey) error {
  210. k := hex.EncodeToString(FromECDSA(key))
  211. return ioutil.WriteFile(file, []byte(k), 0600)
  212. }
  213. // GenerateKey generates a new private key.
  214. func GenerateKey() (*ecdsa.PrivateKey, error) {
  215. return ecdsa.GenerateKey(S256(), rand.Reader)
  216. }
  217. // ValidateSignatureValues verifies whether the signature values are valid with
  218. // the given chain rules. The v value is assumed to be either 0 or 1.
  219. func ValidateSignatureValues(v byte, r, s *big.Int, homestead bool) bool {
  220. if r.Cmp(common.Big1) < 0 || s.Cmp(common.Big1) < 0 {
  221. return false
  222. }
  223. // reject upper range of s values (ECDSA malleability)
  224. // see discussion in secp256k1/libsecp256k1/include/secp256k1.h
  225. if homestead && s.Cmp(secp256k1halfN) > 0 {
  226. return false
  227. }
  228. // Frontier: allow s to be in full N range
  229. return r.Cmp(secp256k1N) < 0 && s.Cmp(secp256k1N) < 0 && (v == 0 || v == 1)
  230. }
  231. func PubkeyToAddress(p ecdsa.PublicKey) common.Address {
  232. pubBytes := FromECDSAPub(&p)
  233. return common.BytesToAddress(Keccak256(pubBytes[1:])[12:])
  234. }
  235. func zeroBytes(bytes []byte) {
  236. for i := range bytes {
  237. bytes[i] = 0
  238. }
  239. }