Here is a quick snippet which shows how to add AES-256, AES-192, or AES-128 GCM encryption to your Golang applications. I needed this for a microservice so I searched around and found this code which really helped me understand it: https://gist.github.com/kkirsche/e28da6754c39d5e7ea10 . But, I changed the code around a bit since the original code generated a random unique nonce during encryption, but required you to set a static nonce for decryption. The change made it more useful in a dynamic situation by extracting the nonce from the resulting cipher after encryption.
My main issue with completely understanding AES-XXX-GCM was how the nonce works, and how the key size controls the encryption block size. I couldn’t seem to find a very basic explanation of everything I wanted to know about it. So, here is an easy chart.
Key length in bytes | Encryption mode |
---|---|
16 | AES-128 |
24 | AES-192 |
32 | AES-256 |
The Key length is crucial and controls whether you will get AES-128, AES-192, or AES-256 encryption out. Notice in the code below, in the main() block, I have a 32 byte key set which will give me AES-256 bit encryption. I also have 2 others commented out just for demonstration purposes.
Encryption
Here are the individual steps made during encryption.
- A new cypher object is created using the provided key. The size of the provided key sets the block size in the returned aes object into the “block” variable.
- Next it will generate a random nonce
- The next step is to put the aes “block” object into GCM mode.
- The last step is to “Seal” or create the encrypted envelope using the provided plain text and nonce and return the resulting cipher.
Decryption
Here are the individual steps made during encryption.
- A new cypher object is created using the provided key. The size of the provided key sets the block size in the returned “aes” object into the “block” variable.
- The next step is to put the “block” aes object into GCM mode.
- It will then check to make sure the cipher still has the nonce prepended to it by doin a length sanity check.
- Next it will extract the nonce from the cipher and store it in the “nonce” variable.
- The last step is where it opens the encrypted envelope given the nonce and full cipher string and returns the original plain text.
Leave a Reply