-
Notifications
You must be signed in to change notification settings - Fork 0
/
aes.go
41 lines (36 loc) · 805 Bytes
/
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
package kgo
import (
"crypto/aes"
"crypto/cipher"
"math/rand"
)
type AESCipher struct {
gcm cipher.AEAD
nonceSize int
}
func (ac *AESCipher) Encrypt(value []byte) ([]byte, error) {
nonce := make([]byte, ac.nonceSize)
_, err := rand.Read(nonce)
if err != nil {
return nil, err
}
return ac.gcm.Seal(nonce, nonce, value, nil), nil
}
func (ac *AESCipher) Decrypt(value []byte) ([]byte, error) {
nonce, value := value[:ac.nonceSize], value[ac.nonceSize:]
return ac.gcm.Open(nil, nonce, value, nil)
}
func CreateAESCipher(key []byte) (*AESCipher, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
ac := new(AESCipher)
ac.gcm = gcm
ac.nonceSize = gcm.NonceSize()
return ac, nil
}