-
Notifications
You must be signed in to change notification settings - Fork 2
/
key.go
103 lines (98 loc) · 2.54 KB
/
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package utils
import (
"crypto/ecdsa"
"fmt"
"os"
"strings"
sdkcrypto "github.com/cosmos/cosmos-sdk/crypto"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
"github.com/ethereum/go-ethereum/accounts/keystore"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
)
func DecryptFxPrivateKey(fxKeyValue, fxPwdValue string) (*secp256k1.PrivKey, error) {
isFile, err := PathExists(fxKeyValue)
if err != nil {
return nil, err
}
if isFile {
keyValueBytes, err := os.ReadFile(fxKeyValue)
if err != nil {
return nil, err
}
existsPwdFile, err := PathExists(fxPwdValue)
if err != nil {
return nil, err
}
var pwdBytes []byte
if existsPwdFile {
pwdBytes, err = os.ReadFile(fxPwdValue)
if err != nil {
return nil, err
}
}
privateKey, _, err := sdkcrypto.UnarmorDecryptPrivKey(string(keyValueBytes), string(pwdBytes))
if err != nil {
return nil, err
}
orcPrivKey, ok := privateKey.(*secp256k1.PrivKey)
if !ok {
return nil, fmt.Errorf("privateKey not secp256k1 privateKey:%v", privateKey)
}
return orcPrivKey, nil
} else if len(fxKeyValue) == 64 || (len(fxKeyValue) == 66 && strings.HasPrefix(fxKeyValue, "0x")) {
keyBytes, err := hexutil.Decode(fxKeyValue)
if err != nil {
return nil, err
}
return &secp256k1.PrivKey{Key: keyBytes}, nil
}
return nil, fmt.Errorf("invalid private key")
}
func DecryptEthPrivateKey(tronKeyValue, tronPwdValue string) (*ecdsa.PrivateKey, error) {
var tronKey *keystore.Key
isFile, err := PathExists(tronKeyValue)
if err != nil {
return nil, err
}
if isFile {
tronKeyValueBytes, err := os.ReadFile(tronKeyValue)
if err != nil {
return nil, err
}
existsPwdFile, err := PathExists(tronPwdValue)
if err != nil {
return nil, err
}
var tronPwdBytes []byte
if existsPwdFile {
tronPwdBytes, err = os.ReadFile(tronPwdValue)
if err != nil {
return nil, err
}
tronKey, err = keystore.DecryptKey(tronKeyValueBytes, string(tronPwdBytes))
if err != nil {
return nil, err
}
} else {
tronKey, err = keystore.DecryptKey(tronKeyValueBytes, tronPwdValue)
if err != nil {
return nil, err
}
}
return tronKey.PrivateKey, nil
} else if len(tronKeyValue) == 64 || (len(tronKeyValue) == 66 && strings.HasPrefix(tronKeyValue, "0x")) {
return crypto.HexToECDSA(tronKeyValue)
}
return nil, fmt.Errorf("invalid private key")
}
func PathExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}