crypto.go 8.4 KB

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