-
Notifications
You must be signed in to change notification settings - Fork 5
/
aes.go
59 lines (47 loc) · 1.2 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
package krypto
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"fmt"
"io"
)
func AesEncrypt(key, authData, plaintext []byte) ([]byte, error) {
iv := make([]byte, 12)
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, fmt.Errorf("generating iv: %w", err)
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, fmt.Errorf("new aes: %w", err)
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("new gcm: %w", err)
}
return aesgcm.Seal(iv, iv, plaintext, authData), nil
}
func AesDecrypt(key, authData, ciphertext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, fmt.Errorf("new aes: %w", err)
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("new gcm: %w", err)
}
ivSize := aesgcm.NonceSize()
if len(ciphertext) < ivSize+1 {
return nil, errors.New("ciphertext too short")
}
iv, cutCiphertext := ciphertext[:ivSize], ciphertext[ivSize:]
return aesgcm.Open(nil, iv, cutCiphertext, authData)
}
func AesRandomKey() ([]byte, error) {
key := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, key); err != nil {
return nil, err
}
return key, nil
}