-
Notifications
You must be signed in to change notification settings - Fork 8
/
crypto.go
54 lines (42 loc) · 1.19 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
package storageredis
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
)
func (rs *RedisStorage) encrypt(bytes []byte) ([]byte, error) {
c, err := aes.NewCipher([]byte(rs.EncryptionKey))
if err != nil {
return nil, fmt.Errorf("Unable to create AES cipher: %v", err)
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return nil, fmt.Errorf("Unable to create GCM cipher: %v", err)
}
nonce := make([]byte, gcm.NonceSize())
_, err = io.ReadFull(rand.Reader, nonce)
if err != nil {
return nil, fmt.Errorf("Unable to generate nonce: %v", err)
}
return gcm.Seal(nonce, nonce, bytes, nil), nil
}
func (rs *RedisStorage) decrypt(bytes []byte) ([]byte, error) {
if len(bytes) < aes.BlockSize {
return nil, fmt.Errorf("Invalid encrypted data")
}
block, err := aes.NewCipher([]byte(rs.EncryptionKey))
if err != nil {
return nil, fmt.Errorf("Unable to create AES cipher: %v", err)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("Unable to create GCM cipher: %v", err)
}
out, err := gcm.Open(nil, bytes[:gcm.NonceSize()], bytes[gcm.NonceSize():], nil)
if err != nil {
return nil, fmt.Errorf("Decryption failure: %v", err)
}
return out, nil
}