-
Notifications
You must be signed in to change notification settings - Fork 88
/
aes.go
111 lines (90 loc) · 2.31 KB
/
aes.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
package crypto
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"github.com/pkg/errors"
)
type AESCipher struct {
key []byte
cipher cipher.AEAD
nonce []byte
}
const keyLength = 24 // 192 bit
func NewAESCypher() (*AESCipher, error) {
key := make([]byte, keyLength)
if _, err := rand.Read(key); err != nil {
return nil, errors.Wrap(err, "failed to read key")
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, errors.Wrap(err, "failed ro create new cipher")
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, errors.Wrap(err, "failed to wrap cipher gcm")
}
nonce := make([]byte, gcm.NonceSize())
if _, err := rand.Read(nonce); err != nil {
return nil, errors.Wrap(err, "failed to read nonce")
}
return &AESCipher{
key: key,
cipher: gcm,
nonce: nonce,
}, nil
}
func AESCipherFromString(data string) (aesCipher *AESCipher, initErr error) {
defer func() {
if r := recover(); r != nil {
initErr = errors.Errorf("cipher init recovered from panic: %v", r)
}
}()
decoded, err := base64.StdEncoding.DecodeString(data)
if err != nil {
initErr = errors.Wrap(err, "failed to decode string")
return
}
if len(decoded) < keyLength {
initErr = errors.Errorf("cipher key is invalid: len=%d, expected %d", len(decoded), keyLength)
return
}
key := decoded[:keyLength]
block, err := aes.NewCipher(key)
if err != nil {
initErr = errors.Wrap(err, "failed to create cipher from data")
return
}
gcm, err := cipher.NewGCM(block)
if err != nil {
initErr = errors.Wrap(err, "failed to wrap cipher gcm")
return
}
nonceLen := len(decoded) - keyLength
if nonceLen < gcm.NonceSize() {
initErr = errors.Errorf("cipher nonce is invalid: len=%d, expected %d", nonceLen, gcm.NonceSize())
return
}
aesCipher = &AESCipher{
key: key,
cipher: gcm,
nonce: decoded[keyLength:],
}
return
}
func (c *AESCipher) ToString() string {
return base64.StdEncoding.EncodeToString(append(c.key, c.nonce...))
}
func (c *AESCipher) Encrypt(in []byte) []byte {
return c.cipher.Seal(nil, c.nonce, in, nil)
}
func (c *AESCipher) Decrypt(in []byte) (result []byte, err error) {
defer func() {
if r := recover(); r != nil {
err = errors.Errorf("decrypt recovered from panic: %v", r)
}
}()
result, err = c.cipher.Open(nil, c.nonce, in, nil)
return
}