@@ -22,12 +22,14 @@ import (
2222 "crypto/rand"
2323 "encoding/hex"
2424 "errors"
25+ "fmt"
2526 "io"
2627 "io/ioutil"
2728 "math/big"
2829 "os"
2930
3031 "github.com/ethereum/go-ethereum/common"
32+ "github.com/ethereum/go-ethereum/common/math"
3133 "github.com/ethereum/go-ethereum/crypto/sha3"
3234 "github.com/ethereum/go-ethereum/rlp"
3335)
@@ -76,23 +78,22 @@ func CreateAddress(b common.Address, nonce uint64) common.Address {
7678}
7779
7880// ToECDSA creates a private key with the given D value.
79- func ToECDSA (prv []byte ) * ecdsa.PrivateKey {
80- if len (prv ) == 0 {
81- return nil
82- }
83-
81+ func ToECDSA (d []byte ) (* ecdsa.PrivateKey , error ) {
8482 priv := new (ecdsa.PrivateKey )
8583 priv .PublicKey .Curve = S256 ()
86- priv .D = new (big.Int ).SetBytes (prv )
87- priv .PublicKey .X , priv .PublicKey .Y = priv .PublicKey .Curve .ScalarBaseMult (prv )
88- return priv
84+ if 8 * len (d ) != priv .Params ().BitSize {
85+ return nil , fmt .Errorf ("invalid length, need %d bits" , priv .Params ().BitSize )
86+ }
87+ priv .D = new (big.Int ).SetBytes (d )
88+ priv .PublicKey .X , priv .PublicKey .Y = priv .PublicKey .Curve .ScalarBaseMult (d )
89+ return priv , nil
8990}
9091
9192func FromECDSA (prv * ecdsa.PrivateKey ) []byte {
9293 if prv == nil {
9394 return nil
9495 }
95- return prv .D . Bytes ( )
96+ return math . PaddedBigBytes ( prv .D , 32 )
9697}
9798
9899func ToECDSAPub (pub []byte ) * ecdsa.PublicKey {
@@ -116,10 +117,7 @@ func HexToECDSA(hexkey string) (*ecdsa.PrivateKey, error) {
116117 if err != nil {
117118 return nil , errors .New ("invalid hex string" )
118119 }
119- if len (b ) != 32 {
120- return nil , errors .New ("invalid length, need 256 bits" )
121- }
122- return ToECDSA (b ), nil
120+ return ToECDSA (b )
123121}
124122
125123// LoadECDSA loads a secp256k1 private key from the given file.
@@ -139,8 +137,7 @@ func LoadECDSA(file string) (*ecdsa.PrivateKey, error) {
139137 if err != nil {
140138 return nil , err
141139 }
142-
143- return ToECDSA (key ), nil
140+ return ToECDSA (key )
144141}
145142
146143// SaveECDSA saves a secp256k1 private key to the given file with
0 commit comments