Merge pull request #14502 from karalabe/mobile-import-ecdsa

Enforce 256 bit keys on raw import, support raw mobile imports
This commit is contained in:
Felix Lange
2017-05-24 22:30:47 +02:00
committed by GitHub
11 changed files with 49 additions and 34 deletions

View File

@ -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