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