-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypt.go
248 lines (220 loc) · 6 KB
/
crypt.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
package cryptoutils
// crypt module provides various ciphers
// for more information see
// https://www.thepolyglotdeveloper.com/2018/02/encrypt-decrypt-data-golang-application-crypto-packages/
// https://github.com/kisom/gocrypto
import (
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
"log"
"strings"
"golang.org/x/crypto/nacl/secretbox"
)
// CreateHash creates a hash for given key
func CreateHash(key string) string {
hasher := md5.New()
hasher.Write([]byte(key))
return hex.EncodeToString(hasher.Sum(nil))
}
// SupportedCiphers provides list of supported ciphers
var SupportedCiphers = []string{"aes", "nacl"}
// Cipher defines cipher interface
type Cipher interface {
Encript(data []byte, key string) ([]byte, error)
Decript(data []byte, key string) ([]byte, error)
}
// CipherAES represents AES Cipher
type CipherAES struct {
}
// Encrypt implementation for AES cipher
func (c *CipherAES) Encrypt(data []byte, passphrase string) ([]byte, error) {
block, _ := aes.NewCipher([]byte(CreateHash(passphrase)))
gcm, err := cipher.NewGCM(block)
if err != nil {
return []byte{}, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return []byte{}, err
}
ciphertext := gcm.Seal(nonce, nonce, data, nil)
return ciphertext, nil
}
// Decrypt implementation for AES Cipher
func (c *CipherAES) Decrypt(data []byte, passphrase string) ([]byte, error) {
key := []byte(CreateHash(passphrase))
block, err := aes.NewCipher(key)
if err != nil {
return []byte{}, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return []byte{}, err
}
nonceSize := gcm.NonceSize()
nonce, ciphertext := data[:nonceSize], data[nonceSize:]
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return []byte{}, err
}
return plaintext, nil
}
const (
// KeySize is the size of a NaCl secret key
KeySize = 32
// NonceSize is the size of a NaCl nonce
NonceSize = 24
)
// GenerateKey creates a new secret key either randomly if input key is
// not provided or via key hash
func GenerateKey(passphrase string) (*[KeySize]byte, error) {
key := new([KeySize]byte)
if passphrase != "" {
hash := []byte(CreateHash(passphrase))
for i, v := range hash {
if i < KeySize {
key[i] = v
}
}
return key, nil
}
_, err := io.ReadFull(rand.Reader, key[:])
if err != nil {
return nil, err
}
return key, nil
}
// GenerateNonce creates a new random nonce.
func GenerateNonce() (*[NonceSize]byte, error) {
nonce := new([NonceSize]byte)
_, err := io.ReadFull(rand.Reader, nonce[:])
if err != nil {
return nil, err
}
return nonce, nil
}
var (
// ErrEncrypt is returned when encryption fails.
ErrEncrypt = errors.New("secret: encryption failed")
// ErrDecrypt is returned when decryption fails.
ErrDecrypt = errors.New("secret: decryption failed")
)
// CipherNaCl represents NaCl Cipher
type CipherNaCl struct {
}
// Encrypt implementation of NaCl cipher
func (c *CipherNaCl) Encrypt(data []byte, passphrase string) ([]byte, error) {
key, err := GenerateKey(passphrase)
if err != nil {
return []byte{}, err
}
nonce, err := GenerateNonce()
if err != nil {
return nil, ErrEncrypt
}
out := make([]byte, len(nonce))
copy(out, nonce[:])
out = secretbox.Seal(out, data, nonce, key)
return out, nil
}
// Decrypt implementation of NaCl cipher
func (c *CipherNaCl) Decrypt(data []byte, passphrase string) ([]byte, error) {
key, err := GenerateKey(passphrase)
if err != nil {
return []byte{}, err
}
if len(data) < (NonceSize + secretbox.Overhead) {
// log.Println("message length is less than nonce size+overhead")
return nil, ErrDecrypt
}
var nonce [NonceSize]byte
copy(nonce[:], data[:NonceSize])
out, ok := secretbox.Open(nil, data[NonceSize:], &nonce, key)
if !ok {
// log.Println("fail to open secret box")
return nil, ErrDecrypt
}
return out, nil
}
// Encrypt wrapper function to encrypt given binary data blob using given passphrase and cipher
func Encrypt(data []byte, passphrase, cipher string) ([]byte, error) {
if strings.ToLower(cipher) == "nacl" {
c := CipherNaCl{}
return c.Encrypt(data, passphrase)
} else if strings.ToLower(cipher) == "aes" {
c := CipherAES{}
return c.Encrypt(data, passphrase)
}
msg := fmt.Sprintf("unsupported cipher %s", cipher)
return []byte{}, errors.New(msg)
}
// Decrypt wrapper function to decrypt given binary data blob using given passphrase and cipher
func Decrypt(data []byte, passphrase, cipher string) ([]byte, error) {
if strings.ToLower(cipher) == "nacl" {
c := CipherNaCl{}
return c.Decrypt(data, passphrase)
} else if strings.ToLower(cipher) == "aes" {
c := CipherAES{}
return c.Decrypt(data, passphrase)
}
msg := fmt.Sprintf("unsupported cipher %s", cipher)
return []byte{}, errors.New(msg)
}
// GetCipher returns either default or given cipher
func GetCipher(cipher string) string {
if cipher == "" {
cipher = SupportedCiphers[0]
}
if InList(cipher, SupportedCiphers) {
log.Fatalf(
"given cipher %s is not supported, please use one from the following %v",
cipher,
SupportedCiphers,
)
}
return strings.ToLower(cipher)
}
// InList checks item in a list
func InList(a string, list []string) bool {
check := 0
for _, b := range list {
if b == a {
check += 1
}
}
if check != 0 {
return true
}
return false
}
// HexDecript decrypts hex encoded cipher string
func HexDecrypt(entry, salt, cipher string) (string, error) {
src := []byte(entry)
dst := make([]byte, hex.DecodedLen(len(src)))
n, err := hex.Decode(dst, src)
if err != nil {
return "", err
}
data, err := Decrypt(dst[:n], salt, cipher)
if err != nil {
return "", err
}
return string(data), nil
}
// HexEncrypt entry entry into hex encoded cipher string
func HexEncrypt(entry, salt, cipher string) (string, error) {
data, err := Encrypt([]byte(entry), salt, cipher)
if err != nil {
return "", err
}
// make hex string out of encrypted data
dst := make([]byte, hex.EncodedLen(len(data)))
hex.Encode(dst, data)
return string(dst), nil
}