-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathprivate_key.go
60 lines (43 loc) · 1.33 KB
/
private_key.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
package tronwallet
import (
"crypto/ecdsa"
"errors"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
)
// GeneratePrivateKey
// Generate a new private key
func GeneratePrivateKey() (*ecdsa.PrivateKey, error) {
return crypto.GenerateKey()
}
// PrivateKeyToHex
// Convert private key to hex string
func PrivateKeyToHex(privateKey *ecdsa.PrivateKey) string {
privateKeyBytes := crypto.FromECDSA(privateKey)
return hexutil.Encode(privateKeyBytes)[2:]
}
// PrivateKeyToBytes
// Convert private key to bytes
func PrivateKeyToBytes(privateKey *ecdsa.PrivateKey) []byte {
return crypto.FromECDSA(privateKey)
}
// PrivateKeyFromHex
// Convert hex string to private key
func PrivateKeyFromHex(privateKeyHex string) (*ecdsa.PrivateKey, error) {
return crypto.HexToECDSA(privateKeyHex)
}
// PrivateKeyFromBytes
// Convert bytes to private key
func PrivateKeyFromBytes(privateKeyBytes []byte) (*ecdsa.PrivateKey, error) {
return crypto.ToECDSA(privateKeyBytes)
}
// PrivateKeyToPublicKey
// Get public key from private key
func PrivateKeyToPublicKey(privateKey *ecdsa.PrivateKey) (*ecdsa.PublicKey, error) {
publicKey := privateKey.Public()
publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
if !ok {
return nil, errors.New("error getting public key from private key")
}
return publicKeyECDSA, nil
}