-
Notifications
You must be signed in to change notification settings - Fork 0
/
aesgcm.go
74 lines (61 loc) · 1.47 KB
/
aesgcm.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
package enshamir
import (
"crypto/aes"
"crypto/cipher"
"fmt"
)
const (
nonceLength = 12
keyLength = 32
)
// https://pkg.go.dev/crypto/cipher#example-NewGCM-Encrypt
func encrypt(key []byte, plaintext []byte) ([]byte, error) {
if len(key) != keyLength {
return nil, fmt.Errorf("AES-256 key should be 32 bytes")
}
aesgcm, err := newAESGCM(key)
if err != nil {
return nil, err
}
nonce, err := randomBytes(nonceLength)
if err != nil {
return nil, err
}
return aesgcm.Seal(nonce, nonce, plaintext, nil), nil
}
// https://pkg.go.dev/crypto/cipher#example-NewGCM-Decrypt
func decrypt(key []byte, cipherText []byte) ([]byte, error) {
if len(key) != keyLength {
return nil, fmt.Errorf("AES-256 key should be 32 bytes")
}
aesgcm, err := newAESGCM(key)
if err != nil {
return nil, err
}
nonce, data, err := extractNonce(cipherText)
if err != nil {
return nil, err
}
if len(nonce) != nonceLength {
return nil, fmt.Errorf("nonce should be 12 bytes")
}
return aesgcm.Open(nil, nonce, data, nil)
}
func extractNonce(cipherText []byte) ([]byte, []byte, error) {
if len(cipherText) < nonceLength {
return nil, nil, fmt.Errorf("invalid data length")
}
nonce, data := cipherText[:nonceLength], cipherText[nonceLength:]
return nonce, data, nil
}
func newAESGCM(key []byte) (cipher.AEAD, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
return aesgcm, nil
}