diff options
author | Péter Szilágyi <peterke@gmail.com> | 2017-05-23 19:58:03 +0800 |
---|---|---|
committer | Péter Szilágyi <peterke@gmail.com> | 2017-05-23 19:58:03 +0800 |
commit | aa73420207cba02a68befdbb8667f1e6ceed3f4d (patch) | |
tree | 76b4fb7ffc9440e7ff27b22dc367355d4fc84f5c /crypto | |
parent | 3556962053267def82f1a9f9e97a26f7b7c1450e (diff) | |
download | go-tangerine-aa73420207cba02a68befdbb8667f1e6ceed3f4d.tar go-tangerine-aa73420207cba02a68befdbb8667f1e6ceed3f4d.tar.gz go-tangerine-aa73420207cba02a68befdbb8667f1e6ceed3f4d.tar.bz2 go-tangerine-aa73420207cba02a68befdbb8667f1e6ceed3f4d.tar.lz go-tangerine-aa73420207cba02a68befdbb8667f1e6ceed3f4d.tar.xz go-tangerine-aa73420207cba02a68befdbb8667f1e6ceed3f4d.tar.zst go-tangerine-aa73420207cba02a68befdbb8667f1e6ceed3f4d.zip |
accounts/keystore, crypto: enforce 256 bit keys on import
Diffstat (limited to 'crypto')
-rw-r--r-- | crypto/crypto.go | 27 |
1 files changed, 12 insertions, 15 deletions
diff --git a/crypto/crypto.go b/crypto/crypto.go index 0b8c06008..d38ffd0d5 100644 --- a/crypto/crypto.go +++ b/crypto/crypto.go @@ -22,12 +22,14 @@ import ( "crypto/rand" "encoding/hex" "errors" + "fmt" "io" "io/ioutil" "math/big" "os" "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/math" "github.com/ethereum/go-ethereum/crypto/sha3" "github.com/ethereum/go-ethereum/rlp" ) @@ -76,23 +78,22 @@ func CreateAddress(b common.Address, nonce uint64) common.Address { } // ToECDSA creates a private key with the given D value. -func ToECDSA(prv []byte) *ecdsa.PrivateKey { - if len(prv) == 0 { - return nil - } - +func ToECDSA(d []byte) (*ecdsa.PrivateKey, error) { priv := new(ecdsa.PrivateKey) priv.PublicKey.Curve = S256() - priv.D = new(big.Int).SetBytes(prv) - priv.PublicKey.X, priv.PublicKey.Y = priv.PublicKey.Curve.ScalarBaseMult(prv) - return priv + if 8*len(d) != priv.Params().BitSize { + return nil, fmt.Errorf("invalid length, need %d bits", priv.Params().BitSize) + } + priv.D = new(big.Int).SetBytes(d) + priv.PublicKey.X, priv.PublicKey.Y = priv.PublicKey.Curve.ScalarBaseMult(d) + return priv, nil } func FromECDSA(prv *ecdsa.PrivateKey) []byte { if prv == nil { return nil } - return prv.D.Bytes() + return math.PaddedBigBytes(prv.D, 32) } func ToECDSAPub(pub []byte) *ecdsa.PublicKey { @@ -116,10 +117,7 @@ func HexToECDSA(hexkey string) (*ecdsa.PrivateKey, error) { if err != nil { return nil, errors.New("invalid hex string") } - if len(b) != 32 { - return nil, errors.New("invalid length, need 256 bits") - } - return ToECDSA(b), nil + return ToECDSA(b) } // LoadECDSA loads a secp256k1 private key from the given file. @@ -139,8 +137,7 @@ func LoadECDSA(file string) (*ecdsa.PrivateKey, error) { if err != nil { return nil, err } - - return ToECDSA(key), nil + return ToECDSA(key) } // SaveECDSA saves a secp256k1 private key to the given file with |