-
Notifications
You must be signed in to change notification settings - Fork 0
/
aes.go
56 lines (44 loc) · 1.1 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
package crypto
import (
"crypto/aes"
"crypto/cipher"
"errors"
"fmt"
)
type AES struct{ cipher cipher.AEAD }
const keyLen = 32
var (
ErrInvalidKey = errors.New("invalid_key")
ErrInvalidCiphertext = errors.New("invalid_ciphertext")
)
func NewAES(key []byte) (*AES, error) {
if len(key) != keyLen {
return nil, ErrInvalidKey
}
b, err := aes.NewCipher(key)
if err != nil {
return nil, fmt.Errorf("failed to create block cipher: %w", err)
}
g, err := cipher.NewGCM(b)
if err != nil {
return nil, fmt.Errorf("failed to create AED cipher: %w", err)
}
return &AES{cipher: g}, nil
}
func (a *AES) Encrypt(plaintext []byte) ([]byte, error) {
nonce, err := RandomBytes(uint(a.cipher.NonceSize()))
if err != nil {
return nil, fmt.Errorf("failed to generate nonce: %w", err)
}
return a.cipher.Seal(nonce, nonce, plaintext, nil), nil
}
func (a *AES) Decrypt(ciphertext []byte) ([]byte, error) {
if len(ciphertext) < a.cipher.NonceSize() {
return nil, ErrInvalidCiphertext
}
return a.cipher.Open(nil,
ciphertext[:a.cipher.NonceSize()],
ciphertext[a.cipher.NonceSize():],
nil,
)
}