Skip to content

Commit 0049c7c

Browse files
committed
Fix security warning on AES encryption
1 parent 538fabe commit 0049c7c

1 file changed

Lines changed: 9 additions & 11 deletions

File tree

pkg/encryption/aes.go

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,6 @@ import (
88
"fmt"
99
)
1010

11-
const AESGCMNonceSize = 12
12-
1311
func EncryptAESGCM(plain, key []byte) (ciphertext, nonce []byte, err error) {
1412
block, err := aes.NewCipher(key)
1513
if err != nil {
@@ -51,7 +49,7 @@ func EncryptAESGCMWithNonceEmbed(plaintext, key []byte) ([]byte, error) {
5149
return nil, fmt.Errorf("failed to create GCM: %w", err)
5250
}
5351

54-
nonce := make([]byte, AESGCMNonceSize)
52+
nonce := make([]byte, aead.NonceSize())
5553
if _, err := rand.Read(nonce); err != nil {
5654
return nil, fmt.Errorf("failed to generate nonce: %w", err)
5755
}
@@ -62,23 +60,23 @@ func EncryptAESGCMWithNonceEmbed(plaintext, key []byte) ([]byte, error) {
6260

6361
// DecryptAESGCMWithNonceEmbed decrypts ciphertext where the nonce is embedded at the start of the slice.
6462
func DecryptAESGCMWithNonceEmbed(data, key []byte) ([]byte, error) {
65-
if len(data) < AESGCMNonceSize {
66-
return nil, errors.New("ciphertext too short")
67-
}
68-
69-
nonce := data[:AESGCMNonceSize]
70-
ciphertext := data[AESGCMNonceSize:]
71-
7263
block, err := aes.NewCipher(key)
7364
if err != nil {
7465
return nil, fmt.Errorf("failed to create AES cipher: %w", err)
7566
}
76-
7767
aead, err := cipher.NewGCM(block)
7868
if err != nil {
7969
return nil, fmt.Errorf("failed to create GCM: %w", err)
8070
}
8171

72+
nonceSize := aead.NonceSize()
73+
if len(data) < nonceSize {
74+
return nil, errors.New("ciphertext too short")
75+
}
76+
77+
nonce := data[:nonceSize]
78+
ciphertext := data[nonceSize:]
79+
8280
plaintext, err := aead.Open(nil, nonce, ciphertext, nil)
8381
if err != nil {
8482
return nil, fmt.Errorf("decryption failed: %w", err)

0 commit comments

Comments
 (0)