/
crypto.go
68 lines (58 loc) · 1.85 KB
/
crypto.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package tools
import (
"crypto/ecdsa"
"encoding/hex"
"github.com/ethereum/go-ethereum/crypto"
"github.com/pkg/errors"
"github.com/ethereum/go-ethereum/common"
)
// PrivToPubKey converts a ECDSA private key to a Ethereum public key.
func PrivToPubKey(privKeyHex string) (string, error) {
privKeyHex, err := sanitizePrivateKey(privKeyHex)
if err != nil {
return "", err
}
privKey, err := crypto.HexToECDSA(privKeyHex)
if err != nil {
return "", errors.Wrapf(err, "error converting private key to ECDSA: %s", privKeyHex)
}
pubKey := privKey.Public()
pubKeyECDSA, ok := pubKey.(*ecdsa.PublicKey)
if !ok {
return "", errors.New("error casting public key to ECDSA")
}
pubKeyBytes := crypto.FromECDSAPub(pubKeyECDSA)
return hex.EncodeToString(pubKeyBytes), nil
}
// PubKeyToAddress converts a public key to an Ethereum address.
func PubKeyToAddress(pubKeyHex string) (string, error) {
pubKeyBytes, err := hex.DecodeString(pubKeyHex)
if err != nil {
return "", err
}
pubKey, err := crypto.UnmarshalPubkey(pubKeyBytes)
if err != nil {
return "", err
}
address := crypto.PubkeyToAddress(*pubKey)
return address.Hex(), nil
}
// GetAddressFromPrivKey() returns the ethereum common.Address from a ecdsa.PrivateKey
func GetAddressFromPrivKey(privateKey *ecdsa.PrivateKey) (address common.Address, err error) {
publicKey := privateKey.Public()
publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
if !ok {
return common.Address{}, errors.New("error casting public key to ECDSA: " + privateKey.D.String())
}
address = crypto.PubkeyToAddress(*publicKeyECDSA)
return
}
// ConvertPrivateKey() converts a private key (hex) string to an ecdsa.PrivateKey
func ConvertPrivateKey(key string) (privateKey *ecdsa.PrivateKey, err error) {
key = RemoveHexPrefix(key)
privateKey, err = crypto.HexToECDSA(key)
if err != nil {
return nil, err
}
return privateKey, nil
}