forked from hashgraph/hedera-sdk-go
/
ed25519_private_key.go
364 lines (294 loc) · 10.5 KB
/
ed25519_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
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
362
363
364
package hedera
/*-
*
* Hedera Go SDK
*
* Copyright (C) 2020 - 2022 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import (
"crypto/ed25519"
"crypto/hmac"
"crypto/rand"
"crypto/sha512"
"encoding/hex"
"encoding/pem"
"fmt"
"io"
"strings"
"github.com/hashgraph/hedera-protobufs-go/services"
"github.com/pkg/errors"
"github.com/youmark/pkcs8"
"golang.org/x/crypto/pbkdf2"
)
// _Ed25519PrivateKey is an ed25519 private key.
type _Ed25519PrivateKey struct {
keyData []byte
chainCode []byte
}
func _GenerateEd25519PrivateKey() (*_Ed25519PrivateKey, error) {
_, privateKey, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return &_Ed25519PrivateKey{}, err
}
return &_Ed25519PrivateKey{
keyData: privateKey,
}, nil
}
// Deprecated
func GeneratePrivateKey() (PrivateKey, error) {
_, privateKey, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return PrivateKey{}, err
}
return PrivateKey{
ed25519PrivateKey: &_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)
switch length {
case 48:
return _Ed25519PrivateKeyFromBytesDer(bytes)
case 32:
return _Ed25519PrivateKeyFromBytesRaw(bytes)
case 64:
return _Ed25519PrivateKeyFromBytesRaw(bytes)
default:
return &_Ed25519PrivateKey{}, _NewErrBadKeyf("invalid private key length: %v bytes", len(bytes))
}
}
// _Ed25519PrivateKeyFromBytes constructs an _Ed25519PrivateKey from a raw slice of either 32 or 64 bytes.
func _Ed25519PrivateKeyFromBytesRaw(bytes []byte) (*_Ed25519PrivateKey, error) {
return &_Ed25519PrivateKey{
keyData: ed25519.NewKeyFromSeed(bytes[0:32]),
}, nil
}
// _Ed25519PrivateKeyFromBytes constructs an _Ed25519PrivateKey from a raw slice of either 32 or 64 bytes.
func _Ed25519PrivateKeyFromBytesDer(byt []byte) (*_Ed25519PrivateKey, error) {
given := hex.EncodeToString(byt)
result := strings.ReplaceAll(given, ed25519PrivateKeyPrefix, "")
decoded, err := hex.DecodeString(result)
if err != nil {
return &_Ed25519PrivateKey{}, err
}
length := len(decoded)
if length != 32 && length != 64 {
return &_Ed25519PrivateKey{}, _NewErrBadKeyf("invalid private key length: %v byt", len(byt))
}
return &_Ed25519PrivateKey{
keyData: ed25519.NewKeyFromSeed(decoded[0:32]),
}, nil
}
// PrivateKeyFromMnemonic 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:]
// 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
}
func _Ed25519PrivateKeyFromString(s string) (*_Ed25519PrivateKey, error) {
bytes, err := hex.DecodeString(strings.ToLower(s))
if err != nil {
return &_Ed25519PrivateKey{}, err
}
return _Ed25519PrivateKeyFromBytes(bytes)
}
// PrivateKeyFromKeystore recovers an _Ed25519PrivateKey from an encrypted _Keystore encoded as a byte slice.
func _Ed25519PrivateKeyFromKeystore(ks []byte, passphrase string) (*_Ed25519PrivateKey, error) {
key, err := _ParseKeystore(ks, passphrase)
if err != nil {
return &_Ed25519PrivateKey{}, err
}
if key.ed25519PrivateKey != nil {
return key.ed25519PrivateKey, nil
}
return &_Ed25519PrivateKey{}, errors.New("only ed25519 keys are currently supported")
}
// PrivateKeyReadKeystore recovers an _Ed25519PrivateKey from an encrypted _Keystore file.
func _Ed25519PrivateKeyReadKeystore(source io.Reader, passphrase string) (*_Ed25519PrivateKey, error) {
keystoreBytes, err := io.ReadAll(source)
if err != nil {
return &_Ed25519PrivateKey{}, err
}
return _Ed25519PrivateKeyFromKeystore(keystoreBytes, passphrase)
}
func _Ed25519PrivateKeyFromPem(bytes []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 pk *pem.Block
for block, rest := pem.Decode(bytes); block != nil; {
if block.Type == blockType {
pk = block
break
}
bytes = rest
if len(bytes) == 0 {
// no key was found
return &_Ed25519PrivateKey{}, _NewErrBadKeyf("pem file did not contain a private key")
}
}
if pk == nil {
// no key was found
return &_Ed25519PrivateKey{}, _NewErrBadKeyf("no PEM data is found")
}
if len(passphrase) == 0 {
// key does not need decrypted, end here
key, err := PrivateKeyFromString(hex.EncodeToString(pk.Bytes))
if err != nil {
return &_Ed25519PrivateKey{}, err
}
return key.ed25519PrivateKey, nil
}
keyI, err := pkcs8.ParsePKCS8PrivateKey(pk.Bytes, []byte(passphrase))
if err != nil {
return &_Ed25519PrivateKey{}, err
}
return _Ed25519PrivateKeyFromBytes(keyI.(ed25519.PrivateKey))
}
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 := io.ReadAll(source)
if err != nil {
return &_Ed25519PrivateKey{}, err
}
return _Ed25519PrivateKeyFromPem(pemFileBytes, passphrase)
}
// _Ed25519PublicKey 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) _StringDer() string {
return fmt.Sprint(ed25519PrivateKeyPrefix, hex.EncodeToString(sk.keyData[:32]))
}
// String returns the text-encoded representation of the _Ed25519PrivateKey.
func (sk _Ed25519PrivateKey) _StringRaw() string {
return hex.EncodeToString(sk.keyData[:32])
}
// _BytesRaw returns the byte slice representation of the _Ed25519PrivateKey.
func (sk _Ed25519PrivateKey) _BytesRaw() []byte {
return sk.keyData[0:32]
}
// _BytesRaw returns the byte slice representation of the _Ed25519PrivateKey.
func (sk _Ed25519PrivateKey) _BytesDer() []byte {
decoded, _ := hex.DecodeString(ed25519PrivateKeyPrefix)
return append(decoded, sk._BytesRaw()...)
}
// 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._BytesRaw(), sk.chainCode, index)
derivedKey, err := _Ed25519PrivateKeyFromBytes(derivedKeyBytes)
if err != nil {
return &_Ed25519PrivateKey{}, err
}
derivedKey.chainCode = chainCode
return derivedKey, nil
}
func (sk _Ed25519PrivateKey) _LegacyDerive(index int64) (*_Ed25519PrivateKey, error) {
keyData := _DeriveLegacyChildKey(sk._BytesRaw(), index)
return _Ed25519PrivateKeyFromBytes(keyData)
}
func (sk _Ed25519PrivateKey) _ToProtoKey() *services.Key {
return sk._PublicKey()._ToProtoKey()
}
func (sk _Ed25519PrivateKey) _SignTransaction(transaction *Transaction) ([]byte, error) {
transaction._RequireOneNodeAccountID()
if transaction.signedTransactions._Length() == 0 {
return make([]byte, 0), errTransactionRequiresSingleNodeAccountID
}
signature := sk._Sign(transaction.signedTransactions._Get(0).(*services.SignedTransaction).GetBodyBytes())
publicKey := sk._PublicKey()
if publicKey == nil {
return []byte{}, errors.New("public key is nil")
}
wrappedPublicKey := PublicKey{
ed25519PublicKey: publicKey,
}
if transaction._KeyAlreadySigned(wrappedPublicKey) {
return []byte{}, nil
}
transaction.transactions = _NewLockableSlice()
transaction.publicKeys = append(transaction.publicKeys, wrappedPublicKey)
transaction.transactionSigners = append(transaction.transactionSigners, nil)
transaction.transactionIDs.locked = true
for index := 0; index < transaction.signedTransactions._Length(); index++ {
temp := transaction.signedTransactions._Get(index).(*services.SignedTransaction)
temp.SigMap.SigPair = append(
temp.SigMap.SigPair,
publicKey._ToSignaturePairProtobuf(signature),
)
transaction.signedTransactions._Set(index, temp)
}
return signature, nil
}