github.com/digdeepmining/go-atheios@v1.5.13-0.20180902133602-d5687a2e6f43/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 "fmt" 25 "io" 26 "io/ioutil" 27 "math/big" 28 "os" 29 30 "encoding/hex" 31 "errors" 32 33 "github.com/atheioschain/go-atheios/common" 34 "github.com/atheioschain/go-atheios/crypto/ecies" 35 "github.com/atheioschain/go-atheios/crypto/secp256k1" 36 "github.com/atheioschain/go-atheios/crypto/sha3" 37 "github.com/atheioschain/go-atheios/rlp" 38 "golang.org/x/crypto/ripemd160" 39 ) 40 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 func Keccak256Hash(data ...[]byte) (h common.Hash) { 50 d := sha3.NewKeccak256() 51 for _, b := range data { 52 d.Write(b) 53 } 54 d.Sum(h[:0]) 55 return h 56 } 57 58 // Deprecated: For backward compatibility as other packages depend on these 59 func Sha3(data ...[]byte) []byte { return Keccak256(data...) } 60 func Sha3Hash(data ...[]byte) common.Hash { return Keccak256Hash(data...) } 61 62 // Creates an ethereum address given the bytes and the nonce 63 func CreateAddress(b common.Address, nonce uint64) common.Address { 64 data, _ := rlp.EncodeToBytes([]interface{}{b, nonce}) 65 return common.BytesToAddress(Keccak256(data)[12:]) 66 } 67 68 func Sha256(data []byte) []byte { 69 hash := sha256.Sum256(data) 70 71 return hash[:] 72 } 73 74 func Ripemd160(data []byte) []byte { 75 ripemd := ripemd160.New() 76 ripemd.Write(data) 77 78 return ripemd.Sum(nil) 79 } 80 81 // Ecrecover returns the public key for the private key that was used to 82 // calculate the signature. 83 // 84 // Note: secp256k1 expects the recover id to be either 0, 1. Ethereum 85 // signatures have a recover id with an offset of 27. Callers must take 86 // this into account and if "recovering" from an Ethereum signature adjust. 87 func Ecrecover(hash, sig []byte) ([]byte, error) { 88 return secp256k1.RecoverPubkey(hash, sig) 89 } 90 91 // New methods using proper ecdsa keys from the stdlib 92 func ToECDSA(prv []byte) *ecdsa.PrivateKey { 93 if len(prv) == 0 { 94 return nil 95 } 96 97 priv := new(ecdsa.PrivateKey) 98 priv.PublicKey.Curve = secp256k1.S256() 99 priv.D = common.BigD(prv) 100 priv.PublicKey.X, priv.PublicKey.Y = secp256k1.S256().ScalarBaseMult(prv) 101 return priv 102 } 103 104 func FromECDSA(prv *ecdsa.PrivateKey) []byte { 105 if prv == nil { 106 return nil 107 } 108 return prv.D.Bytes() 109 } 110 111 func ToECDSAPub(pub []byte) *ecdsa.PublicKey { 112 if len(pub) == 0 { 113 return nil 114 } 115 x, y := elliptic.Unmarshal(secp256k1.S256(), pub) 116 return &ecdsa.PublicKey{Curve: secp256k1.S256(), X: x, Y: y} 117 } 118 119 func FromECDSAPub(pub *ecdsa.PublicKey) []byte { 120 if pub == nil || pub.X == nil || pub.Y == nil { 121 return nil 122 } 123 return elliptic.Marshal(secp256k1.S256(), pub.X, pub.Y) 124 } 125 126 // HexToECDSA parses a secp256k1 private key. 127 func HexToECDSA(hexkey string) (*ecdsa.PrivateKey, error) { 128 b, err := hex.DecodeString(hexkey) 129 if err != nil { 130 return nil, errors.New("invalid hex string") 131 } 132 if len(b) != 32 { 133 return nil, errors.New("invalid length, need 256 bits") 134 } 135 return ToECDSA(b), nil 136 } 137 138 // LoadECDSA loads a secp256k1 private key from the given file. 139 // The key data is expected to be hex-encoded. 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 156 return ToECDSA(key), nil 157 } 158 159 // SaveECDSA saves a secp256k1 private key to the given file with 160 // restrictive permissions. The key data is saved hex-encoded. 161 func SaveECDSA(file string, key *ecdsa.PrivateKey) error { 162 k := hex.EncodeToString(FromECDSA(key)) 163 return ioutil.WriteFile(file, []byte(k), 0600) 164 } 165 166 func GenerateKey() (*ecdsa.PrivateKey, error) { 167 return ecdsa.GenerateKey(secp256k1.S256(), rand.Reader) 168 } 169 170 // ValidateSignatureValues verifies whether the signature values are valid with 171 // the given chain rules. The v value is assumed to be either 0 or 1. 172 func ValidateSignatureValues(v byte, r, s *big.Int, homestead bool) bool { 173 if r.Cmp(common.Big1) < 0 || s.Cmp(common.Big1) < 0 { 174 return false 175 } 176 // reject upper range of s values (ECDSA malleability) 177 // see discussion in secp256k1/libsecp256k1/include/secp256k1.h 178 if homestead && s.Cmp(secp256k1.HalfN) > 0 { 179 return false 180 } 181 // Frontier: allow s to be in full N range 182 return r.Cmp(secp256k1.N) < 0 && s.Cmp(secp256k1.N) < 0 && (v == 0 || v == 1) 183 } 184 185 func SigToPub(hash, sig []byte) (*ecdsa.PublicKey, error) { 186 s, err := Ecrecover(hash, sig) 187 if err != nil { 188 return nil, err 189 } 190 191 x, y := elliptic.Unmarshal(secp256k1.S256(), s) 192 return &ecdsa.PublicKey{Curve: secp256k1.S256(), X: x, Y: y}, nil 193 } 194 195 // Sign calculates an ECDSA signature. 196 // 197 // This function is susceptible to chosen plaintext attacks that can leak 198 // information about the private key that is used for signing. Callers must 199 // be aware that the given hash cannot be chosen by an adversery. Common 200 // solution is to hash any input before calculating the signature. 201 // 202 // The produced signature is in the [R || S || V] format where V is 0 or 1. 203 func Sign(data []byte, prv *ecdsa.PrivateKey) (sig []byte, err error) { 204 if len(data) != 32 { 205 return nil, fmt.Errorf("hash is required to be exactly 32 bytes (%d)", len(data)) 206 } 207 208 seckey := common.LeftPadBytes(prv.D.Bytes(), prv.Params().BitSize/8) 209 defer zeroBytes(seckey) 210 sig, err = secp256k1.Sign(data, seckey) 211 return 212 } 213 214 func Encrypt(pub *ecdsa.PublicKey, message []byte) ([]byte, error) { 215 return ecies.Encrypt(rand.Reader, ecies.ImportECDSAPublic(pub), message, nil, nil) 216 } 217 218 func Decrypt(prv *ecdsa.PrivateKey, ct []byte) ([]byte, error) { 219 key := ecies.ImportECDSA(prv) 220 return key.Decrypt(rand.Reader, ct, nil, nil) 221 } 222 223 func PubkeyToAddress(p ecdsa.PublicKey) common.Address { 224 pubBytes := FromECDSAPub(&p) 225 return common.BytesToAddress(Keccak256(pubBytes[1:])[12:]) 226 } 227 228 func zeroBytes(bytes []byte) { 229 for i := range bytes { 230 bytes[i] = 0 231 } 232 }