github.com/r8d8/go-ethereum@v5.5.2+incompatible/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 "crypto/sha256" 24 "encoding/hex" 25 "errors" 26 "fmt" 27 "io" 28 "math/big" 29 30 "github.com/ethereumproject/go-ethereum/common" 31 "github.com/ethereumproject/go-ethereum/crypto/ecies" 32 "github.com/ethereumproject/go-ethereum/crypto/secp256k1" 33 "github.com/ethereumproject/go-ethereum/crypto/sha3" 34 "github.com/ethereumproject/go-ethereum/rlp" 35 "golang.org/x/crypto/ripemd160" 36 ) 37 38 func Keccak256(data ...[]byte) []byte { 39 d := sha3.NewKeccak256() 40 for _, b := range data { 41 d.Write(b) 42 } 43 return d.Sum(nil) 44 } 45 46 func Keccak256Hash(data ...[]byte) (h common.Hash) { 47 d := sha3.NewKeccak256() 48 for _, b := range data { 49 d.Write(b) 50 } 51 d.Sum(h[:0]) 52 return h 53 } 54 55 // Deprecated: For backward compatibility as other packages depend on these 56 func Sha3(data ...[]byte) []byte { return Keccak256(data...) } 57 func Sha3Hash(data ...[]byte) common.Hash { return Keccak256Hash(data...) } 58 59 // Creates an ethereum address given the bytes and the nonce 60 func CreateAddress(b common.Address, nonce uint64) common.Address { 61 data, _ := rlp.EncodeToBytes([]interface{}{b, nonce}) 62 return common.BytesToAddress(Keccak256(data)[12:]) 63 } 64 65 func Sha256(data []byte) []byte { 66 hash := sha256.Sum256(data) 67 68 return hash[:] 69 } 70 71 func Ripemd160(data []byte) []byte { 72 ripemd := ripemd160.New() 73 ripemd.Write(data) 74 75 return ripemd.Sum(nil) 76 } 77 78 func Ecrecover(hash, sig []byte) ([]byte, error) { 79 return secp256k1.RecoverPubkey(hash, sig) 80 } 81 82 // New methods using proper ecdsa keys from the stdlib 83 func ToECDSA(prv []byte) *ecdsa.PrivateKey { 84 if len(prv) == 0 { 85 return nil 86 } 87 88 priv := new(ecdsa.PrivateKey) 89 priv.PublicKey.Curve = secp256k1.S256() 90 priv.D = new(big.Int).SetBytes(prv) 91 priv.PublicKey.X, priv.PublicKey.Y = secp256k1.S256().ScalarBaseMult(prv) 92 return priv 93 } 94 95 func FromECDSA(prv *ecdsa.PrivateKey) []byte { 96 if prv == nil { 97 return nil 98 } 99 return prv.D.Bytes() 100 } 101 102 func ToECDSAPub(pub []byte) *ecdsa.PublicKey { 103 if len(pub) == 0 { 104 return nil 105 } 106 x, y := elliptic.Unmarshal(secp256k1.S256(), pub) 107 return &ecdsa.PublicKey{Curve: secp256k1.S256(), X: x, Y: y} 108 } 109 110 func FromECDSAPub(pub *ecdsa.PublicKey) []byte { 111 if pub == nil || pub.X == nil || pub.Y == nil { 112 return nil 113 } 114 return elliptic.Marshal(secp256k1.S256(), pub.X, pub.Y) 115 } 116 117 // HexToECDSA parses a secp256k1 private key. 118 func HexToECDSA(hexkey string) (*ecdsa.PrivateKey, error) { 119 b, err := hex.DecodeString(hexkey) 120 if err != nil { 121 return nil, errors.New("invalid hex string") 122 } 123 if len(b) != 32 { 124 return nil, errors.New("invalid length, need 256 bits") 125 } 126 return ToECDSA(b), nil 127 } 128 129 // LoadECDSA loads a secp256k1 private key from the given file. 130 // The key data is expected to be hex-encoded. 131 func LoadECDSA(in io.Reader) (*ecdsa.PrivateKey, error) { 132 buf := make([]byte, 64) 133 if _, err := io.ReadFull(in, buf); err != nil { 134 return nil, err 135 } 136 137 key, err := hex.DecodeString(string(buf)) 138 if err != nil { 139 return nil, err 140 } 141 142 return ToECDSA(key), nil 143 } 144 145 // WriteECDSAKey saves a secp256k1 private key to the given file with 146 // restrictive permissions. The key data is saved hex-encoded. 147 func WriteECDSAKey(to io.Writer, key *ecdsa.PrivateKey) (int, error) { 148 k := hex.EncodeToString(FromECDSA(key)) 149 return to.Write([]byte(k)) 150 } 151 152 func GenerateKey() (*ecdsa.PrivateKey, error) { 153 return ecdsa.GenerateKey(secp256k1.S256(), rand.Reader) 154 } 155 156 func ValidateSignatureValues(v byte, r, s *big.Int, homestead bool) bool { 157 if r.Sign() <= 0 || s.Sign() <= 0 { 158 return false 159 } 160 vint := uint32(v) 161 // reject upper range of s values (ECDSA malleability) 162 // see discussion in secp256k1/libsecp256k1/include/secp256k1.h 163 if homestead && s.Cmp(secp256k1.HalfN) > 0 { 164 return false 165 } 166 // Frontier: allow s to be in full N range 167 if s.Cmp(secp256k1.N) >= 0 { 168 return false 169 } 170 if r.Cmp(secp256k1.N) < 0 && (vint == 27 || vint == 28) { 171 return true 172 } else { 173 return false 174 } 175 } 176 177 func SigToPub(hash, sig []byte) (*ecdsa.PublicKey, error) { 178 s, err := Ecrecover(hash, sig) 179 if err != nil { 180 return nil, err 181 } 182 183 x, y := elliptic.Unmarshal(secp256k1.S256(), s) 184 return &ecdsa.PublicKey{Curve: secp256k1.S256(), X: x, Y: y}, nil 185 } 186 187 func Sign(hash []byte, prv *ecdsa.PrivateKey) (sig []byte, err error) { 188 if len(hash) != 32 { 189 return nil, fmt.Errorf("hash is required to be exactly 32 bytes (%d)", len(hash)) 190 } 191 192 seckey := common.LeftPadBytes(prv.D.Bytes(), prv.Params().BitSize/8) 193 defer zeroBytes(seckey) 194 sig, err = secp256k1.Sign(hash, seckey) 195 return 196 } 197 198 func Encrypt(pub *ecdsa.PublicKey, message []byte) ([]byte, error) { 199 return ecies.Encrypt(rand.Reader, ecies.ImportECDSAPublic(pub), message, nil, nil) 200 } 201 202 func Decrypt(prv *ecdsa.PrivateKey, ct []byte) ([]byte, error) { 203 key := ecies.ImportECDSA(prv) 204 return key.Decrypt(rand.Reader, ct, nil, nil) 205 } 206 207 func PubkeyToAddress(p ecdsa.PublicKey) common.Address { 208 pubBytes := FromECDSAPub(&p) 209 return common.BytesToAddress(Keccak256(pubBytes[1:])[12:]) 210 } 211 212 func zeroBytes(bytes []byte) { 213 for i := range bytes { 214 bytes[i] = 0 215 } 216 }