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