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