github.com/avence12/go-ethereum@v1.5.10-0.20170320123548-1dfd65f6d047/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 "io" 26 "io/ioutil" 27 "math/big" 28 "os" 29 30 "github.com/ethereum/go-ethereum/common" 31 "github.com/ethereum/go-ethereum/crypto/sha3" 32 "github.com/ethereum/go-ethereum/rlp" 33 ) 34 35 var ( 36 secp256k1_N, _ = new(big.Int).SetString("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", 16) 37 secp256k1_halfN = new(big.Int).Div(secp256k1_N, big.NewInt(2)) 38 ) 39 40 // Keccak256 calculates and returns the Keccak256 hash of the input data. 41 func Keccak256(data ...[]byte) []byte { 42 d := sha3.NewKeccak256() 43 for _, b := range data { 44 d.Write(b) 45 } 46 return d.Sum(nil) 47 } 48 49 // Keccak256Hash calculates and returns the Keccak256 hash of the input data, 50 // converting it to an internal Hash data structure. 51 func Keccak256Hash(data ...[]byte) (h common.Hash) { 52 d := sha3.NewKeccak256() 53 for _, b := range data { 54 d.Write(b) 55 } 56 d.Sum(h[:0]) 57 return h 58 } 59 60 // Keccak512 calculates and returns the Keccak512 hash of the input data. 61 func Keccak512(data ...[]byte) []byte { 62 d := sha3.NewKeccak512() 63 for _, b := range data { 64 d.Write(b) 65 } 66 return d.Sum(nil) 67 } 68 69 // Deprecated: For backward compatibility as other packages depend on these 70 func Sha3Hash(data ...[]byte) common.Hash { return Keccak256Hash(data...) } 71 72 // Creates an ethereum address given the bytes and the nonce 73 func CreateAddress(b common.Address, nonce uint64) common.Address { 74 data, _ := rlp.EncodeToBytes([]interface{}{b, nonce}) 75 return common.BytesToAddress(Keccak256(data)[12:]) 76 } 77 78 // ToECDSA creates a private key with the given D value. 79 func ToECDSA(prv []byte) *ecdsa.PrivateKey { 80 if len(prv) == 0 { 81 return nil 82 } 83 84 priv := new(ecdsa.PrivateKey) 85 priv.PublicKey.Curve = S256() 86 priv.D = new(big.Int).SetBytes(prv) 87 priv.PublicKey.X, priv.PublicKey.Y = priv.PublicKey.Curve.ScalarBaseMult(prv) 88 return priv 89 } 90 91 func FromECDSA(prv *ecdsa.PrivateKey) []byte { 92 if prv == nil { 93 return nil 94 } 95 return prv.D.Bytes() 96 } 97 98 func ToECDSAPub(pub []byte) *ecdsa.PublicKey { 99 if len(pub) == 0 { 100 return nil 101 } 102 x, y := elliptic.Unmarshal(S256(), pub) 103 return &ecdsa.PublicKey{Curve: S256(), X: x, Y: y} 104 } 105 106 func FromECDSAPub(pub *ecdsa.PublicKey) []byte { 107 if pub == nil || pub.X == nil || pub.Y == nil { 108 return nil 109 } 110 return elliptic.Marshal(S256(), pub.X, pub.Y) 111 } 112 113 // HexToECDSA parses a secp256k1 private key. 114 func HexToECDSA(hexkey string) (*ecdsa.PrivateKey, error) { 115 b, err := hex.DecodeString(hexkey) 116 if err != nil { 117 return nil, errors.New("invalid hex string") 118 } 119 if len(b) != 32 { 120 return nil, errors.New("invalid length, need 256 bits") 121 } 122 return ToECDSA(b), nil 123 } 124 125 // LoadECDSA loads a secp256k1 private key from the given file. 126 // The key data is expected to be hex-encoded. 127 func LoadECDSA(file string) (*ecdsa.PrivateKey, error) { 128 buf := make([]byte, 64) 129 fd, err := os.Open(file) 130 if err != nil { 131 return nil, err 132 } 133 defer fd.Close() 134 if _, err := io.ReadFull(fd, buf); err != nil { 135 return nil, err 136 } 137 138 key, err := hex.DecodeString(string(buf)) 139 if err != nil { 140 return nil, err 141 } 142 143 return ToECDSA(key), nil 144 } 145 146 // SaveECDSA saves a secp256k1 private key to the given file with 147 // restrictive permissions. The key data is saved hex-encoded. 148 func SaveECDSA(file string, key *ecdsa.PrivateKey) error { 149 k := hex.EncodeToString(FromECDSA(key)) 150 return ioutil.WriteFile(file, []byte(k), 0600) 151 } 152 153 func GenerateKey() (*ecdsa.PrivateKey, error) { 154 return ecdsa.GenerateKey(S256(), rand.Reader) 155 } 156 157 // ValidateSignatureValues verifies whether the signature values are valid with 158 // the given chain rules. The v value is assumed to be either 0 or 1. 159 func ValidateSignatureValues(v byte, r, s *big.Int, homestead bool) bool { 160 if r.Cmp(common.Big1) < 0 || s.Cmp(common.Big1) < 0 { 161 return false 162 } 163 // reject upper range of s values (ECDSA malleability) 164 // see discussion in secp256k1/libsecp256k1/include/secp256k1.h 165 if homestead && s.Cmp(secp256k1_halfN) > 0 { 166 return false 167 } 168 // Frontier: allow s to be in full N range 169 return r.Cmp(secp256k1_N) < 0 && s.Cmp(secp256k1_N) < 0 && (v == 0 || v == 1) 170 } 171 172 func PubkeyToAddress(p ecdsa.PublicKey) common.Address { 173 pubBytes := FromECDSAPub(&p) 174 return common.BytesToAddress(Keccak256(pubBytes[1:])[12:]) 175 } 176 177 func zeroBytes(bytes []byte) { 178 for i := range bytes { 179 bytes[i] = 0 180 } 181 }