Explore KMS with CodeWhisperer (and a Dash of Cryptography) - AES-GCM
Living next to parks, people often forget to appreciate the beauty that's right beside them. Similarly, I almost forgot the awe I had studying KMS API the first time, when I joined the org seven years ago.
Now, with CodeWhisperer's ability to generate scaffolding code in a matter of seconds, I've decided to revisit KMS' API and the basics of cryptography. I aim to do this with fresh eyes, as if I'm a new user, hoping to reignite the passion that I once had.
So, where do we begin? Naturally, with AES-GCM encryption and decryption. This is the foundation of KMS. The entire key management business of KMS revolves around the design of AES-GCM.
I requested CodeWhisperer to generate the code to encrypt and decrypt a message using the KMS API.
Seems simple, doesn't it? Next, I asked CodeWhisper to generate the code to perform the same AES-GCM encryption and decryption with a 256 bits key locally.
That's quite a bit of code, and there are many decisions to make, some of which can be risky if you're not sure what you're doing.
Instead of using a KMS keyId, you need to provide the local AES-GCM cipher with a 256 bits key. This key must be randomly generated; otherwise, the encryption is compromised. It turns out, generating a key with industry-strength entropy is more challenging than you might think.
You also need to provide the AES-GCM cipher with a unique nonce (Initialization Vector), which is a 12-byte number that should never be reused with the same key. Why 12-byte? Well, it's a clever idea. The 12-byte nonce (Number Once, a number or bit string that is used only once) is padded with 4 zero bytes to produce a 16-byte counter. This counter is incremented for each block of plaintext. A 4-byte counter on 128-bit blocks means no more than 2^36 bytes (or 64 GiB) of data can be encrypted before overflowing the counter. Therefore, 64 GiB of data is designated as an upper bound for GCM encryption.
Notice that the cipher text has exactly the same length as the plaintext message. Isn't AES a block cipher? Yes, it is. However, AES-GCM transforms a block cipher like AES into a stream cipher that can work on any plaintext size, no padding needed!
The local decrypt needs 5 parameters. KMS decrypt needs two. As you might have guessed, the ciphertext_blob carries the nonce, tag, KMS keyId, and ciphertext.
Now we can appreciate the one-liner that calls the KMS API for AES-GCM encryption and decryption. It eliminates the messy decisions callers need to make, millions of times every second, 24*7!
Last updated
Was this helpful?