github.com/humaniq/go-ethereum@v1.6.8-0.20171225131628-061223a13848/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/ethereum/go-ethereum/common" 32 "github.com/ethereum/go-ethereum/common/math" 33 "github.com/ethereum/go-ethereum/crypto/sha3" 34 "github.com/ethereum/go-ethereum/rlp" 35 ) 36 37 var ( 38 secp256k1_N, _ = new(big.Int).SetString("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", 16) 39 secp256k1_halfN = new(big.Int).Div(secp256k1_N, big.NewInt(2)) 40 ) 41 42 // Keccak256 calculates and returns the Keccak256 hash of the input data. 43 func Keccak256(data ...[]byte) []byte { 44 d := sha3.NewKeccak256() 45 for _, b := range data { 46 d.Write(b) 47 } 48 return d.Sum(nil) 49 } 50 51 // Keccak256Hash calculates and returns the Keccak256 hash of the input data, 52 // converting it to an internal Hash data structure. 53 func Keccak256Hash(data ...[]byte) (h common.Hash) { 54 d := sha3.NewKeccak256() 55 for _, b := range data { 56 d.Write(b) 57 } 58 d.Sum(h[:0]) 59 return h 60 } 61 62 // Keccak512 calculates and returns the Keccak512 hash of the input data. 63 func Keccak512(data ...[]byte) []byte { 64 d := sha3.NewKeccak512() 65 for _, b := range data { 66 d.Write(b) 67 } 68 return d.Sum(nil) 69 } 70 71 // Creates an ethereum address given the bytes and the nonce 72 func CreateAddress(b common.Address, nonce uint64) common.Address { 73 data, _ := rlp.EncodeToBytes([]interface{}{b, nonce}) 74 return common.BytesToAddress(Keccak256(data)[12:]) 75 } 76 77 // ToECDSA creates a private key with the given D value. 78 func ToECDSA(d []byte) (*ecdsa.PrivateKey, error) { 79 return toECDSA(d, true) 80 } 81 82 // ToECDSAUnsafe blindly converts a binary blob to a private key. It should almost 83 // never be used unless you are sure the input is valid and want to avoid hitting 84 // errors due to bad origin encoding (0 prefixes cut off). 85 func ToECDSAUnsafe(d []byte) *ecdsa.PrivateKey { 86 priv, _ := toECDSA(d, false) 87 return priv 88 } 89 90 // toECDSA creates a private key with the given D value. The strict parameter 91 // controls whether the key's length should be enforced at the curve size or 92 // it can also accept legacy encodings (0 prefixes). 93 func toECDSA(d []byte, strict bool) (*ecdsa.PrivateKey, error) { 94 priv := new(ecdsa.PrivateKey) 95 priv.PublicKey.Curve = S256() 96 if strict && 8*len(d) != priv.Params().BitSize { 97 return nil, fmt.Errorf("invalid length, need %d bits", priv.Params().BitSize) 98 } 99 priv.D = new(big.Int).SetBytes(d) 100 priv.PublicKey.X, priv.PublicKey.Y = priv.PublicKey.Curve.ScalarBaseMult(d) 101 if priv.PublicKey.X == nil { 102 return nil, errors.New("invalid private key") 103 } 104 return priv, nil 105 } 106 107 // FromECDSA exports a private key into a binary dump. 108 func FromECDSA(priv *ecdsa.PrivateKey) []byte { 109 if priv == nil { 110 return nil 111 } 112 return math.PaddedBigBytes(priv.D, priv.Params().BitSize/8) 113 } 114 115 func ToECDSAPub(pub []byte) *ecdsa.PublicKey { 116 if len(pub) == 0 { 117 return nil 118 } 119 x, y := elliptic.Unmarshal(S256(), pub) 120 return &ecdsa.PublicKey{Curve: S256(), X: x, Y: y} 121 } 122 123 func FromECDSAPub(pub *ecdsa.PublicKey) []byte { 124 if pub == nil || pub.X == nil || pub.Y == nil { 125 return nil 126 } 127 return elliptic.Marshal(S256(), pub.X, pub.Y) 128 } 129 130 // HexToECDSA parses a secp256k1 private key. 131 func HexToECDSA(hexkey string) (*ecdsa.PrivateKey, error) { 132 b, err := hex.DecodeString(hexkey) 133 if err != nil { 134 return nil, errors.New("invalid hex string") 135 } 136 return ToECDSA(b) 137 } 138 139 // LoadECDSA loads a secp256k1 private key from the given file. 140 func LoadECDSA(file string) (*ecdsa.PrivateKey, error) { 141 buf := make([]byte, 64) 142 fd, err := os.Open(file) 143 if err != nil { 144 return nil, err 145 } 146 defer fd.Close() 147 if _, err := io.ReadFull(fd, buf); err != nil { 148 return nil, err 149 } 150 151 key, err := hex.DecodeString(string(buf)) 152 if err != nil { 153 return nil, err 154 } 155 return ToECDSA(key) 156 } 157 158 // SaveECDSA saves a secp256k1 private key to the given file with 159 // restrictive permissions. The key data is saved hex-encoded. 160 func SaveECDSA(file string, key *ecdsa.PrivateKey) error { 161 k := hex.EncodeToString(FromECDSA(key)) 162 return ioutil.WriteFile(file, []byte(k), 0600) 163 } 164 165 func GenerateKey() (*ecdsa.PrivateKey, error) { 166 return ecdsa.GenerateKey(S256(), rand.Reader) 167 } 168 169 // ValidateSignatureValues verifies whether the signature values are valid with 170 // the given chain rules. The v value is assumed to be either 0 or 1. 171 func ValidateSignatureValues(v byte, r, s *big.Int, homestead bool) bool { 172 if r.Cmp(common.Big1) < 0 || s.Cmp(common.Big1) < 0 { 173 return false 174 } 175 // reject upper range of s values (ECDSA malleability) 176 // see discussion in secp256k1/libsecp256k1/include/secp256k1.h 177 if homestead && s.Cmp(secp256k1_halfN) > 0 { 178 return false 179 } 180 // Frontier: allow s to be in full N range 181 return r.Cmp(secp256k1_N) < 0 && s.Cmp(secp256k1_N) < 0 && (v == 0 || v == 1) 182 } 183 184 func PubkeyToAddress(p ecdsa.PublicKey) common.Address { 185 pubBytes := FromECDSAPub(&p) 186 return common.BytesToAddress(Keccak256(pubBytes[1:])[12:]) 187 } 188 189 func zeroBytes(bytes []byte) { 190 for i := range bytes { 191 bytes[i] = 0 192 } 193 }