Skip to content

Commit

Permalink
prevent IV collisions for awskms
Browse files Browse the repository at this point in the history
  • Loading branch information
Paddy Steed committed Oct 25, 2023
1 parent 9ff66ea commit 96c73cd
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions providers/awskms/kms.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"encoding/binary"
"fmt"
"io"
"sync/atomic"
"time"

"github.com/aws/aws-sdk-go-v2/aws"
Expand All @@ -33,6 +34,9 @@ type KMSCrypter struct {
// encryptedKeyLength is the length of the DEK.
encryptedKeyLength uint8

// encryptedKeyEncryptionCount is the number of encryptions performed with the current key
encryptedKeyEncryptionCount atomic.Uint64

// cipherBlock is the 256-bit AES GCM block cipher.
aesgcm cipher.AEAD

Expand Down Expand Up @@ -105,10 +109,8 @@ func (k *KMSCrypter) Encrypt(w io.Writer, r io.Reader) error {
return errors.Wrap(err, "failed to read from io.Reader")
}

nonce, err := sqlcrypter.GenerateBytes(k.aesgcm.NonceSize())
if err != nil {
return errors.Wrap(err, "failed to generate 12-byte random nonce")
}
nonce := make([]byte, 12)
binary.LittleEndian.PutUint64(nonce[4:], k.encryptedKeyEncryptionCount.Add(1))

ciphertext := k.aesgcm.Seal(nil, nonce, src.Bytes(), nil)

Expand Down

0 comments on commit 96c73cd

Please # to comment.