Notes
AES
AES is a block cipher. It takes exactly sixteen bytes and a key, and produces sixteen scrambled bytes. Keys are one hundred and twenty eight, one hundred and ninety two or two hundred and fifty six bits. It was standardised in two thousand one, has been attacked by the world's cryptographers ever since, and has no practical break. Modern processors have it built in, so it is very fast. But real data is longer than sixteen bytes, and how you handle that is called the mode.
- a block cipher: 16-byte blocks
- key sizes: 128, 192 or 256 bits
- standardised in 2001, studied ever since; no practical break
- built into CPUs (AES-NI), so it is very fast
- but: AES alone encrypts one block. Real data needs a "mode" to chain blocks
ECB: the wrong mode
The simplest mode, called ECB, encrypts every block separately. That sounds harmless. We encrypted three blocks, two of them identical. The first two blocks of ciphertext came out identical as well. An observer cannot read the data, but can see which parts repeat. Encrypt an image this way and its outline is still visible. Encrypt database fields and equal values reveal themselves. ECB should never be used, and security scanners flag it on sight.
# three 16-byte blocks: A, A, B
c = ecb_encrypt(key,
b"A"*16 + b"A"*16 + b"B"*16)
c[0:16] == c[16:32] # True
c[16:32] == c[32:48] # False
# equal plaintext blocks give
# equal ciphertext blocks:
# the structure shows through AES-GCM
The mode to use is GCM. It does two jobs at once, which is why it is called authenticated encryption. It hides the data, and it produces a tag that detects any change. Here is the whole operation. A thirty two byte key, a twelve byte nonce, the data, and one extra value we will come to. Twenty one bytes of data became thirty seven: the encrypted data plus a sixteen byte tag. This is the default you should reach for.
key = AESGCM.generate_key(256)
nonce = os.urandom(12)
ct = AESGCM(key).encrypt(nonce,
b"card=4111111111111111",
b"order-1001")
len(key), len(nonce), len(ct)
# (32, 12, 37)
# 21 bytes of data + 16-byte tag The tag
Here is why the tag matters. We flipped a single bit of the ciphertext and tried to decrypt. The library raised invalid tag and returned nothing: no partial data, no garbage. Without that check, encryption only hides data; it does not stop an attacker changing it, and with older modes attackers could flip bits to alter amounts or even recover plaintext through error messages. Always use an authenticated mode. If you are offered encryption without a tag, decline.
bad = bytearray(ct); bad[0] ^= 1
AESGCM(key).decrypt(
nonce, bytes(bad), b"order-1001")
# raises InvalidTag
# no partial plaintext, no
# garbage: nothing is returned
# encryption without this check
# can be modified by an attacker Associated data
That extra value is called associated data. It is not secret and not encrypted, but it is covered by the tag. We encrypted with the order number one thousand and one as associated data, then tried to decrypt claiming order one thousand and two. It failed. That stops an attacker copying a valid encrypted value from one record into another, such as pasting a high-privilege user's encrypted role into their own row. Bind every ciphertext to its record and its tenant.
# encrypted with b"order-1001"
AESGCM(key).decrypt(
nonce, ct, b"order-1002")
# raises InvalidTag
# associated data is not secret
# and not encrypted, but it is
# covered by the tag
# use it for: record id, tenant
# id, key version, column name The nonce
GCM has one rule that must never be broken. The nonce, which means number used once, must be unique for every encryption under the same key. It is not secret and is stored next to the ciphertext. But if you ever encrypt two messages with the same key and the same nonce, an attacker can combine them to learn about both and forge tags. Random twelve byte nonces are safe for about four billion messages per key, which is one reason keys are rotated.
- 12 bytes, not secret, stored beside the ciphertext
- must be unique for every encryption under one key
- reuse it once and an attacker can recover the XOR of the two messages and forge tags
- random nonces: fine up to about 4 billion messages per key; then rotate the key
ChaCha20 and speed
There is one other cipher worth knowing: ChaCha twenty with Poly thirteen oh five. It is also authenticated, and it is fast on phones and small chips that lack built-in AES. We timed both on one hundred megabytes. AES took zero point zero seven nine seconds and ChaCha zero point zero eight six, more than a gigabyte per second on one core. So when someone says encryption would be too slow, measure first. It almost never is the bottleneck.
AES-256-GCM 0.079 s ChaCha20-Poly1305 0.086 s # over 1 GB per second, one core # encryption is not your # performance problem # ChaCha20-Poly1305: also # authenticated; fast on phones # and chips without AES built in
The key
All of this depends on the key. Generate it from a cryptographic random source; never use a password directly as a key. Two hundred and fifty six bits is the usual choice. Never hard-code it, commit it or log it. Keep it away from the data it protects, in a key management service or a secret manager, because an attacker who steals a database and finds the key beside it has everything. Use different keys for different purposes, and plan how to rotate them.
- generate with a cryptographic random source, never from a password directly
- 256 bits is the usual choice
- never hard-code it or commit it; never log it
- keep it apart from the data: a KMS or secret manager
- different keys for different purposes
- plan rotation (episode 11)
In practice
In practice you rarely call AES yourself. TLS uses it for data in transit. Disks and volumes use it through LUKS, BitLocker and cloud disk encryption. Databases offer transparent encryption, and applications add field-level encryption for the most sensitive columns. Object storage encrypts with keys from a key management service. And in your own code, prefer a high-level library that picks the mode and handles nonces for you, so there is less to get wrong.
- in transit: TLS does it
- disks and volumes: LUKS, BitLocker, cloud disk encryption
- databases: TDE, or field-level encryption in the app
- object storage: server-side encryption with KMS keys
- in code: a high-level library (Tink, libsodium, Fernet)
Common mistakes
Mistakes. ECB mode. Encryption without authentication, such as plain CBC or counter mode with no tag. A reused or fixed nonce, which destroys GCM's guarantees. A hard-coded key in the source. A password used directly as the key. The key stored in the same database or the same bucket as the data. And one key used for every purpose, forever, so a single leak exposes everything ever encrypted.
- ECB mode
- encryption with no authentication (plain CBC or CTR)
- a reused or fixed nonce
- a hard-coded key
- a password used as the key
- the key stored with the data
- one key for everything, forever
Say it like this
In the interview: I would use AES two fifty six in GCM mode through a vetted library, because it is authenticated encryption, so any tampering makes decryption fail. Each encryption gets a unique nonce, stored with the ciphertext, and I bind the ciphertext to its record with associated data. Keys are generated and held in a key management service, never stored beside the data, and rotated. And I would never use ECB or unauthenticated modes.
- "AES-256-GCM through a vetted
- library: authenticated, so tampering fails. A unique
- nonce per encryption, stored
- with the ciphertext, and associated data binding it to the record. Keys come from a KMS, never stored with the data, and are rotated."