I am implementing client-side encryption for data stored in AWS DynamoDB, and was wondering about the correct use of AWS KMS for key management in addition to using AES/GCM.
I am using the master key stored in AWS KMS to generate a data key used for encryption. I am also using AWS KMS to generate a random number for initializing the IV.
My code looks roughly like so:
GenerateDataKeyResult dataKeyResult = kmsClient.generateDataKey( new GenerateDataKeyRequest() .withKeyId("masterKeyId") .withKeySpec(DataKeySpec.AES_128) .addEncryptionContextEntry("encContext", "aValue")); ByteBuffer plaintextKey = dataKeyResult.getPlaintext(); ByteBuffer encryptedKey = dataKeyResult.getCiphertextBlob(); GenerateRandomRequest randomRequest = new GenerateRandomRequest().withNumberOfBytes(12); GenerateRandomResult randomResult = kmsClient.generateRandom(randomRequest); byte nonce = randomResult.getPlaintext().array(); GCMParameterSpec spec = new GCMParameterSpec(16 * 8, nonce); SecretKeySpec secretKeySpec = new SecretKeySpec(plaintextKey.array(), "AES"); Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC"); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, spec); byte aad = "Whatever I like".getBytes(); cipher.updateAAD(aad); String data = "Hello, World!"; byte cipherText = cipher.doFinal(data.getBytes());
In theory that seems to work, but I am not fully confident in that I am using it correctly. In particular:
I will store the
encryptedKeywith the encrypted data, but can I use the same key for all rows or do I need to generate a new one for each one?
How does the
AADfactor into this? Do I need to store it? Does it need to be unique per row?
Do I need to generate a new nonce for each row of data? Can I store it together with the data?
So far my assumptions are:
- I can reuse the same key for all rows
- I need to generate a new nonce for each row
- I will store the nonce with each row, and additionally store the
- The AAD is the same for all rows and I can generate it in a deterministic way so I do not need to store it
Am I in the ballpark regarding my assumptions?
(I also do apologize if the belongs in StackOverflow, I was a bit unsure of where to post this)