github.com/vantum/vantum@v0.0.0-20180815184342-fe37d5f7a990/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/vantum/vantum/common" 32 "github.com/vantum/vantum/common/math" 33 "github.com/vantum/vantum/crypto/sha3" 34 "github.com/vantum/vantum/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 101 // The priv.D must < N 102 if priv.D.Cmp(secp256k1_N) >= 0 { 103 return nil, fmt.Errorf("invalid private key, >=N") 104 } 105 // The priv.D must not be zero or negative. 106 if priv.D.Sign() <= 0 { 107 return nil, fmt.Errorf("invalid private key, zero or negative") 108 } 109 110 priv.PublicKey.X, priv.PublicKey.Y = priv.PublicKey.Curve.ScalarBaseMult(d) 111 if priv.PublicKey.X == nil { 112 return nil, errors.New("invalid private key") 113 } 114 return priv, nil 115 } 116 117 // FromECDSA exports a private key into a binary dump. 118 func FromECDSA(priv *ecdsa.PrivateKey) []byte { 119 if priv == nil { 120 return nil 121 } 122 return math.PaddedBigBytes(priv.D, priv.Params().BitSize/8) 123 } 124 125 func ToECDSAPub(pub []byte) *ecdsa.PublicKey { 126 if len(pub) == 0 { 127 return nil 128 } 129 x, y := elliptic.Unmarshal(S256(), pub) 130 return &ecdsa.PublicKey{Curve: S256(), X: x, Y: y} 131 } 132 133 func FromECDSAPub(pub *ecdsa.PublicKey) []byte { 134 if pub == nil || pub.X == nil || pub.Y == nil { 135 return nil 136 } 137 return elliptic.Marshal(S256(), pub.X, pub.Y) 138 } 139 140 // HexToECDSA parses a secp256k1 private key. 141 func HexToECDSA(hexkey string) (*ecdsa.PrivateKey, error) { 142 b, err := hex.DecodeString(hexkey) 143 if err != nil { 144 return nil, errors.New("invalid hex string") 145 } 146 return ToECDSA(b) 147 } 148 149 // LoadECDSA loads a secp256k1 private key from the given file. 150 func LoadECDSA(file string) (*ecdsa.PrivateKey, error) { 151 buf := make([]byte, 64) 152 fd, err := os.Open(file) 153 if err != nil { 154 return nil, err 155 } 156 defer fd.Close() 157 if _, err := io.ReadFull(fd, buf); err != nil { 158 return nil, err 159 } 160 161 key, err := hex.DecodeString(string(buf)) 162 if err != nil { 163 return nil, err 164 } 165 return ToECDSA(key) 166 } 167 168 // SaveECDSA saves a secp256k1 private key to the given file with 169 // restrictive permissions. The key data is saved hex-encoded. 170 func SaveECDSA(file string, key *ecdsa.PrivateKey) error { 171 k := hex.EncodeToString(FromECDSA(key)) 172 return ioutil.WriteFile(file, []byte(k), 0600) 173 } 174 175 func GenerateKey() (*ecdsa.PrivateKey, error) { 176 return ecdsa.GenerateKey(S256(), rand.Reader) 177 } 178 179 // ValidateSignatureValues verifies whether the signature values are valid with 180 // the given chain rules. The v value is assumed to be either 0 or 1. 181 func ValidateSignatureValues(v byte, r, s *big.Int, homestead bool) bool { 182 if r.Cmp(common.Big1) < 0 || s.Cmp(common.Big1) < 0 { 183 return false 184 } 185 // reject upper range of s values (ECDSA malleability) 186 // see discussion in secp256k1/libsecp256k1/include/secp256k1.h 187 if homestead && s.Cmp(secp256k1_halfN) > 0 { 188 return false 189 } 190 // Frontier: allow s to be in full N range 191 return r.Cmp(secp256k1_N) < 0 && s.Cmp(secp256k1_N) < 0 && (v == 0 || v == 1) 192 } 193 194 func PubkeyToAddress(p ecdsa.PublicKey) common.Address { 195 pubBytes := FromECDSAPub(&p) 196 return common.BytesToAddress(Keccak256(pubBytes[1:])[12:]) 197 } 198 199 func zeroBytes(bytes []byte) { 200 for i := range bytes { 201 bytes[i] = 0 202 } 203 }