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