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