-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathguts.go
443 lines (321 loc) · 13.4 KB
/
guts.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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
// jeffCoin 4. WALLET guts.go
package wallet
import (
"crypto/aes"
"crypto/cipher"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"encoding/hex"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"io/ioutil"
"math/big"
"reflect"
"github.com/btcsuite/btcutil/base58"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/ripemd160"
)
func checkErr(err error) {
if err != nil {
fmt.Printf("Error is %+v\n", err)
log.Fatal("ERROR:", err)
}
}
// WALLET ****************************************************************************************************************
// getWallet - Gets the wallet
func getWallet() walletStruct {
s := "START getWallet() - Gets the wallet"
log.Debug("WALLET: GUTS " + s)
s = "END getWallet() - Gets the wallet"
log.Debug("WALLET: GUTS " + s)
return wallet
}
// makeWallet - Creates the wallet and writes to file (Keys and jeffCoin Address)
func makeWallet(nodeName string, passwordString string) walletStruct {
s := "START makeWallet() - Creates the wallet and writes to file (Keys and jeffCoin Address)"
log.Debug("WALLET: GUTS " + s)
// GENERATE ECDSA KEYS
privateKeyHex, publicKeyHex := generateECDSASKeys()
// GENERATE JEFFCOIN ADDRESS
jeffCoinAddressHex := generatejeffCoinAddress(publicKeyHex)
// LOAD KEYS & JEFFCOIN ADDRESS IN WALLET STRUCT
wallet = walletStruct{privateKeyHex, publicKeyHex, jeffCoinAddressHex}
// Create keyText from passwordString
keyByte32 := sha256.Sum256([]byte(passwordString))
keyByte := keyByte32[:]
// ENCRYPT privateKeyHex using key
// keyText := "myverystrongpasswordo32bitlength"
// keyByte := []byte(keyText)
additionalData := "Jeff's additional data for authorization"
privateKeyHexEncrypted := encryptAES(keyByte, privateKeyHex, additionalData)
// ENCRYPTED STRUCT FOR FILE
walletStructEncrypted := walletStruct{privateKeyHexEncrypted, publicKeyHex, jeffCoinAddressHex}
// WRITE WALLET STRUCT TO JSON FILE
filedata, _ := json.MarshalIndent(walletStructEncrypted, "", " ")
filename := "credentials/" + nodeName + "-wallet-encrypted.json"
_ = ioutil.WriteFile(filename, filedata, 0644)
s = "Wrote wallet to " + filename
log.Info("WALLET: GUTS " + s)
s = "END makeWallet() - Creates the wallet and writes to file (Keys and jeffCoin Address)"
log.Debug("WALLET: GUTS " + s)
return wallet
}
// readWalletFile - Reads the wallet from a file and puts in struct
func readWalletFile(nodeName string, passwordString string) walletStruct {
s := "START readWalletFile() - Reads the wallet from a file and puts in struct"
log.Debug("WALLET: GUTS " + s)
var walletStructEncrypted walletStruct
// READ WALLET STRUCT TO JSON FILE
filename := "credentials/" + nodeName + "-wallet-encrypted.json"
filedata, _ := ioutil.ReadFile(filename)
_ = json.Unmarshal([]byte(filedata), &walletStructEncrypted)
s = "Read wallet from " + filename
log.Info("WALLET: GUTS " + s)
// Create keyText from passwordString
keyByte32 := sha256.Sum256([]byte(passwordString))
keyByte := keyByte32[:]
// DECRYPT privateKeyHex using key
// keyText := "myverystrongpasswordo32bitlength"
// keyByte := []byte(keyText)
additionalData := "Jeff's additional data for authorization"
privateKeyHex := decryptAES(keyByte, walletStructEncrypted.PrivateKeyHex, additionalData)
// PLACE privateKeyHex IN STRUCT
wallet = walletStructEncrypted
wallet.PrivateKeyHex = privateKeyHex
s = "END readWalletFile() - Reads the wallet from a file and puts in struct"
log.Debug("WALLET: GUTS " + s)
return wallet
}
// KEYS ******************************************************************************************************************
// generateECDSASKeys - Generate privateKeyHex and publicKeyHex
func generateECDSASKeys() (string, string) {
s := "START generateECDSASKeys() - Generate privateKeyHex and publicKeyHex"
log.Debug("WALLET: GUTS " + s)
// GET PRIVATE & PUBLIC KEY PAIR
curve := elliptic.P256()
privateKeyRaw, err := ecdsa.GenerateKey(curve, rand.Reader)
checkErr(err)
// EXTRACT PUBLIC KEY
publicKeyRaw := &privateKeyRaw.PublicKey
// ENCODE
privateKeyHex, publicKeyHex := encodeKeys(privateKeyRaw, publicKeyRaw)
// DECODE TO CHECK
privateKeyRawCheck, publicKeyRawCheck := decodeKeys(privateKeyHex, publicKeyHex)
// CHECK THEY ARE THE SAME
if !reflect.DeepEqual(privateKeyRaw, privateKeyRawCheck) {
s = "ERROR: Private keys do not match"
log.Error("WALLET: GUTS " + s)
}
if !reflect.DeepEqual(publicKeyRaw, publicKeyRawCheck) {
s = "ERROR: Public keys do not match"
log.Error("WALLET: GUTS " + s)
}
s = "END generateECDSASKeys() - Generate privateKeyHex and publicKeyHex"
log.Debug("WALLET: GUTS " + s)
return privateKeyHex, publicKeyHex
}
// encodeKeys - Encodes privateKeyRaw & publicKeyRaw to privateKeyHex & publicKeyHex
func encodeKeys(privateKeyRaw *ecdsa.PrivateKey, publicKeyRaw *ecdsa.PublicKey) (string, string) {
s := "START encodeKeys() - Encodes privateKeyRaw & publicKeyRaw to privateKeyHex & publicKeyHex"
log.Debug("WALLET: GUTS " + s)
privateKeyx509Encoded, _ := x509.MarshalECPrivateKey(privateKeyRaw)
privateKeyPEM := pem.EncodeToMemory(
&pem.Block{
Type: "PRIVATE KEY",
Bytes: privateKeyx509Encoded,
})
privateKeyHex := hex.EncodeToString(privateKeyPEM)
publicKeyx509Encoded, _ := x509.MarshalPKIXPublicKey(publicKeyRaw)
publicKeyPEM := pem.EncodeToMemory(
&pem.Block{
Type: "PUBLIC KEY",
Bytes: publicKeyx509Encoded,
})
publicKeyHex := hex.EncodeToString(publicKeyPEM)
s = "END encodeKeys() - Encodes privateKeyRaw & publicKeyRaw to privateKeyHex & publicKeyHex"
log.Debug("WALLET: GUTS " + s)
return privateKeyHex, publicKeyHex
}
// decodeKeys - Decodes privateKeyHex & publicKeyHex to privateKeyRaw & publicKeyRaw
func decodeKeys(privateKeyHex string, publicKeyHex string) (*ecdsa.PrivateKey, *ecdsa.PublicKey) {
s := "START decodeKeys() - Decodes privateKeyHex & publicKeyHex to privateKeyRaw & publicKeyRaw"
log.Debug("WALLET: GUTS " + s)
privateKeyPEM, _ := hex.DecodeString(privateKeyHex)
block, _ := pem.Decode([]byte(privateKeyPEM))
privateKeyx509Encoded := block.Bytes
privateKeyRaw, _ := x509.ParseECPrivateKey(privateKeyx509Encoded)
publicKeyPEM, _ := hex.DecodeString(publicKeyHex)
blockPub, _ := pem.Decode([]byte(publicKeyPEM))
publicKeyx509Encoded := blockPub.Bytes
genericPublicKey, _ := x509.ParsePKIXPublicKey(publicKeyx509Encoded)
publicKeyRaw := genericPublicKey.(*ecdsa.PublicKey)
s = "END decodeKeys() - Decodes privateKeyHex & publicKeyHex to privateKeyRaw & publicKeyRaw"
log.Debug("WALLET: GUTS " + s)
return privateKeyRaw, publicKeyRaw
}
// JEFFCOIN ADDRESS ******************************************************************************************************
// generatejeffCoinAddress - Creates a jeffCoin Address
func generatejeffCoinAddress(publicKeyHex string) string {
s := "START generatejeffCoinAddress() - Creates a jeffCoin Address"
log.Debug("WALLET: GUTS " + s)
verPublicKeyHash := hashPublicKey(publicKeyHex)
checkSum := checksumKeyHash(verPublicKeyHash)
jeffCoinAddressHex := encodeKeyHash(verPublicKeyHash, checkSum)
s = "END generatejeffCoinAddress() - Creates a jeffCoin Address"
log.Debug("WALLET: GUTS " + s)
return jeffCoinAddressHex
}
// hashPublicKey - Hashes publicKeyHex
func hashPublicKey(publicKeyHex string) []byte {
s := "START hashPublicKey() - Hashes publicKeyHex"
log.Debug("WALLET: GUTS " + s)
// 1 - SHA-256 HASH
publicKeyByte, _ := hex.DecodeString(publicKeyHex) // Don't use []byte(publicKeyHex)
publicSHA256 := sha256.Sum256(publicKeyByte)
s = "1 - SHA-256 HASH: " + hex.EncodeToString(publicSHA256[:])
log.Info("WALLET: GUTS " + s)
// 2 - RIPEMD-160 HASH
RIPEMD160Hasher := ripemd160.New()
_, err := RIPEMD160Hasher.Write(publicSHA256[:])
checkErr(err)
publicKeyHash := RIPEMD160Hasher.Sum(nil)
s = "2 - RIPEMD-160 HASH: " + hex.EncodeToString(publicKeyHash)
log.Info("WALLET: GUTS " + s)
// VERSION
version := make([]byte, 1)
version[0] = 0x00
s = "VERSION: " + "00"
log.Info("WALLET: GUTS " + s)
// 3 - CONCAT
verPublicKeyHash := append(version, publicKeyHash...)
s = "3 - CONCAT " + hex.EncodeToString(verPublicKeyHash)
log.Info("WALLET: GUTS " + s)
s = "END hashPublicKey() - Hashes publicKeyHex"
log.Debug("WALLET: GUTS " + s)
return verPublicKeyHash
}
// checksumKeyHash - Checksums verPublicKeyHash
func checksumKeyHash(verPublicKeyHash []byte) []byte {
s := "START checksumKeyHash() - Checksums verPublicKeyHash"
log.Debug("WALLET: GUTS " + s)
// 4 - SHA-256 HASH
firstpublicSHA256 := sha256.Sum256(verPublicKeyHash)
s = "4 - SHA-256 HASH " + hex.EncodeToString(firstpublicSHA256[:])
log.Info("WALLET: GUTS " + s)
// 5 - SHA-256 HASH
secondPublicSHA256 := sha256.Sum256(firstpublicSHA256[:])
s = "5 - SHA-256 HASH " + hex.EncodeToString(secondPublicSHA256[:])
log.Info("WALLET: GUTS " + s)
// 6 - FIRST FOUR BYTE
checkSum := secondPublicSHA256[:4]
s = "6 - FIRST FOUR BYTE " + hex.EncodeToString(checkSum)
log.Info("WALLET: GUTS " + s)
s = "END checksumKeyHash() - Checksums verPublicKeyHash"
log.Debug("WALLET: GUTS " + s)
return checkSum
}
// encodeKeyHash - Encodes verPublicKeyHash & checkSum
func encodeKeyHash(verPublicKeyHash []byte, checkSum []byte) string {
s := "START encodeKeyHash() - Encodes verPublicKeyHash & checkSum"
log.Debug("WALLET: GUTS " + s)
// 7 - CONCAT
addressHex := append(verPublicKeyHash, checkSum...)
s = "7 - CONCAT " + hex.EncodeToString(addressHex)
log.Info("WALLET: GUTS " + s)
// 8 - BASE58 ENCODING
jeffCoinAddressHex := base58.Encode(addressHex)
s = "8 - BASE58 ENCODING " + jeffCoinAddressHex
log.Info("WALLET: GUTS " + s)
s = "END encodeKeyHash() - Encodes verPublicKeyHash & checkSum"
log.Debug("WALLET: GUTS " + s)
return jeffCoinAddressHex
}
// SIGNATURE *************************************************************************************************************
// createSignature - Creates a ECDSA Digital Signature
func createSignature(privateKeyHex string, plainText string) string {
s := "START createSignature() - Creates a ECDSA Digital Signature"
log.Debug("WALLET: GUTS " + s)
// DECODE PRIVATE KEY
privateKeyPEM, _ := hex.DecodeString(privateKeyHex)
block, _ := pem.Decode([]byte(privateKeyPEM))
privateKeyx509Encoded := block.Bytes
privateKeyRaw, _ := x509.ParseECPrivateKey(privateKeyx509Encoded)
// HASH plainText
hashedPlainText := sha256.Sum256([]byte(plainText))
hashedPlainTextByte := hashedPlainText[:]
r := big.NewInt(0)
ss := big.NewInt(0)
// CREATE SIGNATURE
r, ss, err := ecdsa.Sign(
rand.Reader,
privateKeyRaw,
hashedPlainTextByte,
)
checkErr(err)
signatureByte := r.Bytes()
signatureByte = append(signatureByte, ss.Bytes()...)
// ENCODE - RETURN HEX
signature := hex.EncodeToString(signatureByte)
s = "END createSignature() - Creates a ECDSA Digital Signature"
log.Debug("WALLET: GUTS " + s)
return signature
}
// ENCRYPT/DECRYPT TEXT **************************************************************************************************
// encryptAES - AES-256 GCM (Galois/Counter Mode) mode encryption
func encryptAES(keyByte []byte, plaintext string, additionalData string) string {
s := "START encryptAES() - AES-256 GCM (Galois/Counter Mode) mode encryption"
log.Debug("WALLET: GUTS " + s)
plaintextByte := []byte(plaintext)
additionalDataByte := []byte(additionalData)
// GET CIPHER BLOCK USING KEY
block, err := aes.NewCipher(keyByte)
checkErr(err)
// GET GCM INSTANCE THAT USES THE AES CIPHER
gcm, err := cipher.NewGCM(block)
checkErr(err)
// CREATE A NONCE
nonce := make([]byte, gcm.NonceSize())
// Populates the nonce with a cryptographically secure random sequence
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
panic(err.Error())
}
// ENCRYPT DATA
// Note how we put the Nonce in the beginging,
// So we can rip it out when we decrypt
cipherTextByte := gcm.Seal(nonce, nonce, plaintextByte, additionalDataByte)
s = "END encryptAES() - AES-256 GCM (Galois/Counter Mode) mode encryption"
log.Debug("WALLET: GUTS " + s)
// RETURN HEX
cipherText := hex.EncodeToString(cipherTextByte)
return cipherText
}
// decryptAES - AES-256 GCM (Galois/Counter Mode) mode decryption
func decryptAES(keyByte []byte, cipherText string, additionalData string) string {
s := "START decryptAES() - AES-256 GCM (Galois/Counter Mode) mode decryption"
log.Debug("WALLET: GUTS " + s)
cipherTextByte, _ := hex.DecodeString(cipherText)
additionalDataByte := []byte(additionalData)
// GET CIPHER BLOCK USING KEY
block, err := aes.NewCipher(keyByte)
checkErr(err)
// GET GCM BLOCK
gcm, err := cipher.NewGCM(block)
checkErr(err)
// EXTRACT NONCE FROM cipherTextByte
// Because I put it there
nonceSize := gcm.NonceSize()
nonce, cipherTextByte := cipherTextByte[:nonceSize], cipherTextByte[nonceSize:]
// DECRYPT DATA
plainTextByte, err := gcm.Open(nil, nonce, cipherTextByte, additionalDataByte)
checkErr(err)
s = "END decryptAES() - AES-256 GCM (Galois/Counter Mode) mode decryption"
log.Debug("WALLET: GUTS " + s)
// RETURN STRING
plainText := string(plainTextByte[:])
return plainText
}