forked from hiero-ledger/hiero-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
crypto.go
361 lines (278 loc) · 9.87 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
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
package hedera
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha512"
"encoding/asn1"
"encoding/binary"
"encoding/hex"
"encoding/pem"
"fmt"
"golang.org/x/crypto/ed25519"
"golang.org/x/crypto/pbkdf2"
"io"
"io/ioutil"
"strings"
"github.com/hashgraph/hedera-sdk-go/proto"
)
const ed25519PrivateKeyPrefix = "302e020100300506032b657004220420"
const ed25519PubKeyPrefix = "302a300506032b6570032100"
type PublicKey interface {
toProto() *proto.Key
}
func publicKeyFromProto(pbKey *proto.Key) (PublicKey, error) {
switch key := pbKey.GetKey().(type) {
case *proto.Key_Ed25519:
return Ed25519PublicKeyFromBytes(key.Ed25519)
case *proto.Key_ThresholdKey:
threshold := key.ThresholdKey.GetThreshold()
keys, err := publicKeyListFromProto(key.ThresholdKey.GetKeys())
if err != nil {
return nil, err
}
return NewThresholdKey(threshold).AddAll(keys), nil
case *proto.Key_KeyList:
keys, err := publicKeyListFromProto(key.KeyList)
if err != nil {
return nil, err
}
return NewKeyList().AddAll(keys), nil
default:
return nil, newErrBadKeyf("key type not implemented: %v", key)
}
}
func publicKeyListFromProto(pb *proto.KeyList) ([]PublicKey, error) {
var keys []PublicKey = make([]PublicKey, len(pb.Keys))
for i, pbKey := range pb.Keys {
key, err := publicKeyFromProto(pbKey)
if err != nil {
return nil, err
}
keys[i] = key
}
return keys, nil
}
// Ed25519PrivateKey is an ed25519 private key.
type Ed25519PrivateKey struct {
keyData []byte
chainCode []byte
}
// Ed25519PublicKey is an ed25519 public key.
type Ed25519PublicKey struct {
keyData []byte
}
// GenerateEd25519PrivateKey generates a random new Ed25519PrivateKey.
func GenerateEd25519PrivateKey() (Ed25519PrivateKey, error) {
_, privateKey, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return Ed25519PrivateKey{}, err
}
return Ed25519PrivateKey{
keyData: privateKey,
}, nil
}
// Ed25519PrivateKeyFromBytes constructs an Ed25519PrivateKey from a raw slice of either 32 or 64 bytes.
func Ed25519PrivateKeyFromBytes(bytes []byte) (Ed25519PrivateKey, error) {
length := len(bytes)
if length != 32 && length != 64 {
return Ed25519PrivateKey{}, newErrBadKeyf("invalid private key length: %v bytes", len(bytes))
}
return Ed25519PrivateKey{
keyData: ed25519.NewKeyFromSeed(bytes[0:32]),
}, nil
}
// Ed25519PrivateKeyFromMnemonic recovers an Ed25519PrivateKey from a valid 24 word length mnemonic phrase and a
// passphrase.
//
// An empty string can be passed for passPhrase If the mnemonic phrase wasn't generated with a passphrase. This is
// required to recover a private key from a mnemonic generated by the Android and iOS wallets.
func Ed25519PrivateKeyFromMnemonic(mnemonic Mnemonic, passPhrase string) (Ed25519PrivateKey, error) {
salt := []byte("mnemonic" + passPhrase)
seed := pbkdf2.Key([]byte(mnemonic.String()), salt, 2048, 64, sha512.New)
h := hmac.New(sha512.New, []byte("ed25519 seed"))
_, err := h.Write(seed)
if err != nil {
return Ed25519PrivateKey{}, err
}
digest := h.Sum(nil)
keyBytes := digest[0:32]
chainCode := digest[32:len(digest)]
// note the index is for derivation, not the index of the slice
for _, index := range []uint32{44, 3030, 0, 0} {
keyBytes, chainCode = deriveChildKey(keyBytes, chainCode, index)
}
privateKey, err := Ed25519PrivateKeyFromBytes(keyBytes)
if err != nil {
return Ed25519PrivateKey{}, err
}
privateKey.chainCode = chainCode
return privateKey, nil
}
// Ed25519PrivateKeyFromString recovers an Ed25519PrivateKey from its text-encoded representation.
func Ed25519PrivateKeyFromString(s string) (Ed25519PrivateKey, error) {
sLen := len(s)
if sLen != 64 && sLen != 96 && sLen != 128 {
return Ed25519PrivateKey{}, newErrBadKeyf("invalid private key string with length %v", len(s))
}
bytes, err := hex.DecodeString(strings.TrimPrefix(strings.ToLower(s), ed25519PrivateKeyPrefix))
if err != nil {
return Ed25519PrivateKey{}, err
}
return Ed25519PrivateKeyFromBytes(bytes)
}
// Ed25519PrivateKeyFromKeystore recovers an Ed25519PrivateKey from an encrypted keystore encoded as a byte slice.
func Ed25519PrivateKeyFromKeystore(ks []byte, passphrase string) (Ed25519PrivateKey, error) {
return parseKeystore(ks, passphrase)
}
// Ed25519PrivateKeyReadKeystore recovers an Ed25519PrivateKey from an encrypted keystore file.
func Ed25519PrivateKeyReadKeystore(source io.Reader, passphrase string) (Ed25519PrivateKey, error) {
keystoreBytes, err := ioutil.ReadAll(source)
if err != nil {
return Ed25519PrivateKey{}, err
}
return Ed25519PrivateKeyFromKeystore(keystoreBytes, passphrase)
}
func Ed25519PrivateKeyFromPem(pemBytes []byte, passphrase string) (Ed25519PrivateKey, error) {
var blockType string
if len(passphrase) == 0 {
blockType = "PRIVATE KEY"
} else {
// the pem is encrypted
blockType = "ENCRYPTED PRIVATE KEY"
}
var PKBlock pem.Block
for block, remaining := pem.Decode(pemBytes); block != nil; {
if block.Type == blockType {
PKBlock = *block
break
}
pemBytes = remaining
if len(pemBytes) < 1 {
// no key was found
return Ed25519PrivateKey{}, newErrBadKeyf("pem file did not contain a private key")
}
}
if len(passphrase) == 0 {
// key does not need decrypted, end here
return Ed25519PrivateKeyFromString(hex.EncodeToString(PKBlock.Bytes))
}
fmt.Println("hello world")
var contents struct {
Contents asn1.RawContent
Key asn1.BitString
}
_, err := asn1.Unmarshal(PKBlock.Bytes, &contents)
fmt.Println(hex.EncodeToString(contents.Contents))
fmt.Println(contents.Key)
if err != nil {
return Ed25519PrivateKey{}, newErrBadKeyf("failed to parse encrypted private key: %s", err.Error())
}
return Ed25519PrivateKeyFromString(hex.EncodeToString(PKBlock.Bytes))
}
func Ed25519PrivateKeyReadPem(source io.Reader, passphrase string) (Ed25519PrivateKey, error) {
// note: Passphrases are currently not supported, but included in the function definition to avoid breaking
// changes in the future.
pemFileBytes, err := ioutil.ReadAll(source)
if err != nil {
return Ed25519PrivateKey{}, err
}
return Ed25519PrivateKeyFromPem(pemFileBytes, passphrase)
}
// Ed25519PublicKeyFromString recovers an Ed25519PublicKey from its text-encoded representation.
func Ed25519PublicKeyFromString(s string) (Ed25519PublicKey, error) {
sLen := len(s)
if sLen != 64 && sLen != 88 {
return Ed25519PublicKey{}, newErrBadKeyf("invalid public key '%v' string with length %v", s, sLen)
}
keyStr := strings.TrimPrefix(strings.ToLower(s), ed25519PubKeyPrefix)
bytes, err := hex.DecodeString(keyStr)
if err != nil {
return Ed25519PublicKey{}, err
}
return Ed25519PublicKey{bytes}, nil
}
// Ed25519PublicKeyFromBytes constructs a known Ed25519PublicKey from its text-encoded representation.
func Ed25519PublicKeyFromBytes(bytes []byte) (Ed25519PublicKey, error) {
if len(bytes) != ed25519.PublicKeySize {
return Ed25519PublicKey{}, newErrBadKeyf("invalid public key length: %v bytes", len(bytes))
}
return Ed25519PublicKey{
keyData: bytes,
}, nil
}
// SLIP-10/BIP-32 Child Key derivation
func deriveChildKey(parentKey []byte, chainCode []byte, index uint32) ([]byte, []byte) {
h := hmac.New(sha512.New, chainCode)
input := make([]byte, 37)
// 0x00 + parentKey + index(BE)
input[0] = 0
copy(input[1:37], parentKey)
binary.BigEndian.PutUint32(input[33:37], index)
// harden the input
input[33] |= 128
h.Write(input)
digest := h.Sum(nil)
return digest[0:32], digest[32:len(digest)]
}
// PublicKey returns the Ed25519PublicKey associated with this Ed25519PrivateKey.
func (sk Ed25519PrivateKey) PublicKey() Ed25519PublicKey {
return Ed25519PublicKey{
keyData: sk.keyData[32:],
}
}
// String returns the text-encoded representation of the Ed25519PrivateKey.
func (sk Ed25519PrivateKey) String() string {
return fmt.Sprint(ed25519PrivateKeyPrefix, hex.EncodeToString(sk.keyData[:32]))
}
// String returns the text-encoded representation of the Ed25519PublicKey.
func (pk Ed25519PublicKey) String() string {
return fmt.Sprint(ed25519PubKeyPrefix, hex.EncodeToString(pk.keyData))
}
// Bytes returns the byte slice representation of the Ed25519PrivateKey.
func (sk Ed25519PrivateKey) Bytes() []byte {
return sk.keyData
}
// Keystore returns an encrypted keystore containing the Ed25519PrivateKey.
func (sk Ed25519PrivateKey) Keystore(passphrase string) ([]byte, error) {
return newKeystore(sk.keyData, passphrase)
}
// WriteKeystore writes an encrypted keystore containing the Ed25519PrivateKey to the provided destination.
func (sk Ed25519PrivateKey) WriteKeystore(destination io.Writer, passphrase string) error {
keystore, err := sk.Keystore(passphrase)
if err != nil {
return err
}
_, err = destination.Write(keystore)
return err
}
// Sign signs the provided message with the Ed25519PrivateKey.
func (sk Ed25519PrivateKey) Sign(message []byte) []byte {
return ed25519.Sign(sk.keyData, message)
}
// SupportsDerivation returns true if the Ed25519PrivateKey supports derivation.
func (sk Ed25519PrivateKey) SupportsDerivation() bool {
return sk.chainCode != nil
}
// Derive a child key compatible with the iOS and Android wallets using a provided wallet/account index. Use index 0 for
// the default account.
//
// This will fail if the key does not support derivation which can be checked by calling SupportsDerivation()
func (sk Ed25519PrivateKey) Derive(index uint32) (Ed25519PrivateKey, error) {
if !sk.SupportsDerivation() {
return Ed25519PrivateKey{}, newErrBadKeyf("child key cannot be derived from this key")
}
derivedKeyBytes, chainCode := deriveChildKey(sk.Bytes(), sk.chainCode, index)
derivedKey, err := Ed25519PrivateKeyFromBytes(derivedKeyBytes)
if err != nil {
return Ed25519PrivateKey{}, err
}
derivedKey.chainCode = chainCode
return derivedKey, nil
}
// Bytes returns the byte slice representation of the Ed25519PublicKey.
func (pk Ed25519PublicKey) Bytes() []byte {
return pk.keyData
}
func (pk Ed25519PublicKey) toProto() *proto.Key {
return &proto.Key{Key: &proto.Key_Ed25519{Ed25519: pk.keyData}}
}