forked from thrasher-corp/gocryptotrader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config_encryption.go
110 lines (88 loc) · 2.33 KB
/
config_encryption.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
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"fmt"
"io"
"log"
)
const (
ENCRYPTION_CONFIRMATION_STRING = "THORS-HAMMER"
)
func PromptForConfigEncryption() bool {
log.Println("Would you like to encrypt your config file (y/n)?")
input := ""
_, err := fmt.Scanln(&input)
if err != nil {
return false
}
if !YesOrNo(input) {
bot.config.EncryptConfig = CONFIG_FILE_ENCRYPTION_DISABLED
SaveConfig()
return false
}
return true
}
func PromptForConfigKey() ([]byte, error) {
var cryptoKey []byte
for len(cryptoKey) != 32 {
log.Println("Enter password (32 characters):")
_, err := fmt.Scanln(&cryptoKey)
if err != nil {
return nil, err
}
if len(cryptoKey) > 32 || len(cryptoKey) < 32 {
fmt.Println("Please re-enter password (32 characters):")
}
}
nonce := make([]byte, 12)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
return cryptoKey, nil
}
func EncryptConfigFile(configData, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
ciphertext := make([]byte, aes.BlockSize+len(configData))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(ciphertext[aes.BlockSize:], configData)
appendedFile := []byte(ENCRYPTION_CONFIRMATION_STRING)
appendedFile = append(appendedFile, ciphertext...)
return appendedFile, nil
}
func DecryptConfigFile(configData, key []byte) ([]byte, error) {
configData = RemoveECS(configData)
blockDecrypt, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
if len(configData) < aes.BlockSize {
return nil, errors.New("The config file data is too small for the AES required block size.")
}
iv := configData[:aes.BlockSize]
configData = configData[aes.BlockSize:]
stream := cipher.NewCFBDecrypter(blockDecrypt, iv)
stream.XORKeyStream(configData, configData)
result := configData
return result, nil
}
func ConfirmConfigJSON(file []byte, result interface{}) error {
return JSONDecode(file, &result)
}
func ConfirmECS(file []byte) bool {
subslice := []byte(ENCRYPTION_CONFIRMATION_STRING)
return bytes.Contains(file, subslice)
}
func RemoveECS(file []byte) []byte {
return bytes.Trim(file, ENCRYPTION_CONFIRMATION_STRING)
}