From aa73420207cba02a68befdbb8667f1e6ceed3f4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C3=A9ter=20Szil=C3=A1gyi?= Date: Tue, 23 May 2017 14:58:03 +0300 Subject: accounts/keystore, crypto: enforce 256 bit keys on import --- crypto/crypto.go | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) (limited to 'crypto/crypto.go') 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 -- cgit v1.2.3