Choosing a Cryptographic Primitive's
own "Not substitutes" section names the one gap left open across the site's other seven Cryptography
entries, then leaves it there: a real handshake needs, "for the bulk of the actual data, once a secret
is agreed — a fast symmetric cipher this site hasn't built yet, a genuine gap rather than an oversight
papered over here." This page closes it. AES (Advanced Encryption Standard — Daemen
and Rijmen's Rijndael, selected by NIST in 2001 and standardized as FIPS-197) is a symmetric block
cipher: the same 128-bit key both encrypts and decrypts, unlike every asymmetric entry already on this
site (RSA Encryption, Diffie–Hellman Key Exchange), where encryption
and decryption use two different keys. It's also the first page on this site to build arithmetic over
GF(2⁸), the finite field Rijndael's own byte-substitution and column-mixing steps are
defined over — nothing this site's other Cryptography or Number Theory entries needed before now.
Generate a random 128-bit key, then encrypt one 16-byte block — AES's own fixed unit of work, no more and no less — and decrypt it back. Everything in this first demo is a single block; see Pitfalls for exactly where that stops being safe for a real multi-block message.
Type a message below. Exactly 16 bytes of it get encrypted — padded with trailing spaces if shorter, truncated if longer (a teaching shortcut, not a real padding scheme; see Pitfalls for why PKCS#7 exists instead):
Now the pitfall. Type a message of up to 32 bytes below — the first and second 16-byte halves are encrypted completely independently under the same key. That's ECB (Electronic Codebook), the simplest and least safe way to extend a block cipher past one block. The default below has two identical 16-byte halves on purpose:
Now the fix. CBC (Cipher Block Chaining) XORs each plaintext block with the previous ciphertext block before encrypting it, so every block's output depends on every block before it — not just its own plaintext. The first block has no previous ciphertext to use, so it's XORed with a random IV (initialization vector) instead, generated fresh per message and sent alongside the ciphertext (it isn't secret — it only has to never repeat under the same key). Same key, same message as the ECB demo above, same two identical 16-byte halves:
A third shape: counter mode. CTR never runs the block cipher on the
plaintext at all. It encrypts a counter — a 16-byte value that starts at a random
initial counter block and increments by one (as a single big-endian 128-bit number,
wrapping on overflow) for every block of the message — to produce a block of keystream, then
XORs that keystream with the plaintext. (Real deployments conventionally split the counter into a fixed
nonce prefix plus a separately incrementing suffix, so the structure is visible rather than implicit;
this page's own incrementCounter just increments the whole 128-bit value, which is simpler
and exactly as correct as long as the initial counter block itself never repeats under the same key, the
same requirement either way — see Pitfalls.) Decryption runs the
identical operation: regenerate the same keystream from the same counter and XOR again (XOR is
its own inverse), so aesCtrCrypt below is both the encrypt and the decrypt
function — there is no separate inverse cipher to define at all, unlike ECB/CBC above. Same key, same
two identical 16-byte halves as the ECB demo:
A fourth mode: authenticated encryption. None of ECB, CBC, or CTR above can tell a
tampered ciphertext from a genuine one — decryption always produces some plaintext, right or
wrong, with nothing built in to say which. GCM (Galois/Counter Mode) runs CTR exactly
as built above to encrypt, then computes a separate 16-byte authentication tag over
the ciphertext — and over any associated data, header-style bytes sent alongside the
message that need to be authenticated but not hidden (a protocol version, a sender ID) — using
GHASH, a second finite-field construction distinct from AES's own GF(2⁸): this
one multiplies 128-bit blocks in GF(2¹²⁸). Decryption recomputes that same tag
independently and refuses to return any plaintext at all if it doesn't match byte-for-byte; see
Why it works for the construction. GCM conventionally uses a 96-bit nonce,
not CBC/CTR's 128-bit IV/initial counter block above (a structural requirement of the nonce-to-counter
construction below, not an arbitrary choice) — generate one, then try encrypting and verifying a
message with associated data:
A 16-byte block is laid out as a 4×4 byte matrix, filled column by column (byte 0 is row 0 of column 0, byte 1 is row 1 of column 0, byte 4 is row 0 of column 1, and so on) — that layout is the state, and every step below operates on it in place. AES-128 uses an 128-bit (16-byte, 4-word) key and runs 10 rounds; AES-192 and AES-256 use longer keys and 12 or 14 rounds instead, not built on this page.
Key schedule (Rijndael key expansion). The 4 words of the original key become 44
words — 11 round keys of 4 words (16 bytes) each. Words 0–3 are the key itself; every later word
w[i] is w[i-4] ⊕ w[i-1], except every 4th word, where w[i-1]
first gets rotated one byte left (RotWord), run through the same S-box SubBytes
uses (SubWord), and XORed with a round constant Rcon[i/4] before the XOR with
w[i-4]. That one round constant per group of four words breaks a symmetry a pure
rotate-and-substitute step would otherwise have across every round key, which is the entire reason
Rcon exists.
Round structure. Round 0 is just AddRoundKey — XOR the state with round
key 0, nothing else. Rounds 1–9 each run, in order: SubBytes, ShiftRows,
MixColumns, AddRoundKey. Round 10 runs the same three steps but
skips MixColumns — the standard's own asymmetry, not an oversight: one more
mixing pass after the final key has already been applied would just need to be undone again to decrypt,
for no added security.
SubBytes replaces every byte with SBOX[byte] — a fixed,
256-entry lookup table that is the cipher's only nonlinear step. (The real S-box is built from each
byte's multiplicative inverse in GF(2⁸) composed with a fixed affine transform; this page
uses the standard's own published table directly rather than re-deriving it, the same "extract, don't
invent" choice this site already makes for SHA-256's round constants.) ShiftRows
cyclically shifts row r left by r positions (row 0 untouched, row 3 shifted by
3) — the only step that moves a byte between columns, without which MixColumns below would
only ever mix bytes that started in the same column, forever. MixColumns
treats each 4-byte column as a degree-3 polynomial over GF(2⁸) and multiplies it by a fixed
polynomial, modulo x⁴+1 — concretely, gmul below is carry-less ("XOR instead of
add") polynomial multiplication, reduced modulo the fixed byte polynomial x⁸+x⁴+x³+x+1
(0x11b) whenever a product would overflow 8 bits. The combination of ShiftRows
and MixColumns is what makes AES diffuse: change one input byte, and after two full rounds
every byte of the state has been touched.
Decryption runs the straightforward inverse cipher: apply the 11 round keys in
reverse order, and undo each step with its inverse (InvShiftRows, InvSubBytes,
InvMixColumns) in reverse order within each round. Real libraries often restructure this
into an algebraically equivalent "equivalent inverse cipher" that runs faster by reordering steps so the
same key schedule can be reused with fewer transformations — not built here, to keep decryption a
direct, readable mirror of encryption rather than a faster but harder-to-follow variant.
GCM's counter, J0. Given a 96-bit nonce, J0 is the nonce
followed by a fixed 32-bit field holding the integer 1 — nonce.concat([0,0,0,1])
above. Encryption runs gctr (the same keystream-XOR idea as aesCtrCrypt above,
generalized to byte arrays so a non-block-aligned message needs no padding) starting from
inc32(J0), not J0 itself — J0 is reserved for the tag step below,
so no counter value is ever reused between the two. inc32 only increments the last 4
bytes, wrapping at 2³² and never carrying into the nonce above them — a different function from
this page's own incrementCounter above, which carries across the full 16 bytes; GCM's own
spec mandates inc32 specifically so the nonce half of the block never changes no matter how
long the message gets, up to the standard's 2³²-block limit. (This page's own demo never gets close to
that limit — see Pitfalls for what that means for verification.)
GHASH, authentication in GF(2¹²⁸). Where MixColumns
multiplies 8-bit values reduced modulo the fixed byte polynomial x⁸+x⁴+x³+x+1,
gmul128 multiplies whole 128-bit (16-byte) values reduced modulo
x¹²⁸+x⁷+x²+x+1 — a different field, same carry-less ("XOR instead of add") shape, just 16×
wider. GHASH folds a message into one 128-bit digest by running
Y through Y ← (Y ⊕ block) • H for every 16-byte block in turn, starting from
Y₀ = 0, where H = E(key, 0¹²⁸) — AES encrypting the all-zero block under the
message key — is a secret subkey derived once per key, never sent anywhere. The blocks fed in are, in
order: the associated data (zero-padded to a 16-byte boundary), the ciphertext (zero-padded the same
way), and one final block holding the bit-lengths of each as two 64-bit big-endian integers — that
trailing length block is what stops an attacker from shifting bytes between the associated-data and
ciphertext regions undetected, the same kind of boundary-confusion attack a missing length prefix enables
elsewhere. The tag is GHASH's output XORed with E(key, J0) — encrypting
J0 itself, the one counter value gctr above never touches — so recovering the
tag from the ciphertext alone would require inverting AES, not just GHASH.
The exact code both demos above call. gmul is the carry-less finite-field
multiplication every MixColumns/InvMixColumns call reduces to:
var SBOX = [ /* 256-entry Rijndael S-box — the standard's own fixed table */
0x63, 0x7c, 0x77, 0x7b, /* … */ 0xb0, 0x54, 0xbb, 0x16
];
var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
function gmul(a, b) { // carry-less multiply, reduced mod x^8+x^4+x^3+x+1 (0x11b)
var p = 0;
for (var i = 0; i < 8; i++) {
if (b & 1) p ^= a;
var hi = a & 0x80;
a = (a << 1) & 0xff;
if (hi) a ^= 0x1b;
b >>= 1;
}
return p;
}
function keyExpansionAES128(key) { // key: 16 bytes -> 44 words (11 round keys of 4 words each)
var w = new Array(44);
for (var i = 0; i < 4; i++) w[i] = [key[4*i], key[4*i+1], key[4*i+2], key[4*i+3]];
for (i = 4; i < 44; i++) {
var temp = w[i-1];
if (i % 4 === 0) {
var rot = [temp[1], temp[2], temp[3], temp[0]]; // RotWord
var sub = [SBOX[rot[0]], SBOX[rot[1]], SBOX[rot[2]], SBOX[rot[3]]]; // SubWord
temp = [sub[0] ^ RCON[i / 4], sub[1], sub[2], sub[3]];
}
w[i] = [w[i-4][0]^temp[0], w[i-4][1]^temp[1], w[i-4][2]^temp[2], w[i-4][3]^temp[3]];
}
return w;
}
function mixColumns(state) { // state: 16 bytes, column-major; in place
for (var c = 0; c < 4; c++) {
var a0 = state[4*c], a1 = state[4*c+1], a2 = state[4*c+2], a3 = state[4*c+3];
state[4*c] = gmul(a0,2) ^ gmul(a1,3) ^ a2 ^ a3;
state[4*c+1] = a0 ^ gmul(a1,2) ^ gmul(a2,3) ^ a3;
state[4*c+2] = a0 ^ a1 ^ gmul(a2,2) ^ gmul(a3,3);
state[4*c+3] = gmul(a0,3) ^ a1 ^ a2 ^ gmul(a3,2);
}
}
function aes128Encrypt(block, key) {
var w = keyExpansionAES128(key);
var state = block.slice();
addRoundKey(state, roundKeyBytes(w, 0));
for (var round = 1; round <= 9; round++) {
subBytes(state); shiftRows(state); mixColumns(state);
addRoundKey(state, roundKeyBytes(w, round));
}
subBytes(state); shiftRows(state);
addRoundKey(state, roundKeyBytes(w, 10)); // round 10: no mixColumns
return state;
}
function aes128Decrypt(block, key) {
var w = keyExpansionAES128(key);
var state = block.slice();
addRoundKey(state, roundKeyBytes(w, 10));
for (var round = 9; round >= 1; round--) {
invShiftRows(state); invSubBytes(state);
addRoundKey(state, roundKeyBytes(w, round));
invMixColumns(state);
}
invShiftRows(state); invSubBytes(state);
addRoundKey(state, roundKeyBytes(w, 0));
return state;
}
function xorBlock(a, b) { // 16-byte XOR, used to chain blocks together
var out = new Array(16);
for (var i = 0; i < 16; i++) out[i] = a[i] ^ b[i];
return out;
}
function aesCbcEncrypt(blocks, key, iv) { // blocks: array of 16-byte arrays
var out = [], prev = iv;
for (var i = 0; i < blocks.length; i++) {
var ct = aes128Encrypt(xorBlock(blocks[i], prev), key); // XOR with previous ciphertext first
out.push(ct);
prev = ct; // this block's ciphertext chains to the next
}
return out;
}
function aesCbcDecrypt(ctBlocks, key, iv) {
var out = [], prev = iv;
for (var i = 0; i < ctBlocks.length; i++) {
out.push(xorBlock(aes128Decrypt(ctBlocks[i], key), prev)); // undo the chaining XOR after decrypting
prev = ctBlocks[i];
}
return out;
}
function incrementCounter(block) { // 128-bit big-endian increment, full block, wraps on overflow
var out = block.slice();
for (var i = 15; i >= 0; i--) {
out[i] = (out[i] + 1) & 0xff;
if (out[i] !== 0) break; // no carry needed — stop here
}
return out;
}
function aesCtrCrypt(blocks, key, icb) { // one function for both directions — see "Why it works"
var out = [], counter = icb;
for (var i = 0; i < blocks.length; i++) {
var keystream = aes128Encrypt(counter, key); // encrypt the counter, not the data
out.push(xorBlock(blocks[i], keystream)); // XOR the keystream with the data
counter = incrementCounter(counter);
}
return out;
}
function inc32(block) { // GCM's own increment — last 4 bytes only, never carries into the nonce above
var out = block.slice();
for (var i = 15; i >= 12; i--) {
out[i] = (out[i] + 1) & 0xff;
if (out[i] !== 0) break;
}
return out;
}
function gctr(key, icb, bytes) { // CTR over a byte array; a partial final block XORs only its own length
var out = [], counter = icb;
for (var i = 0; i < bytes.length; i += 16) {
var chunk = bytes.slice(i, i + 16);
var keystream = aes128Encrypt(counter, key);
for (var j = 0; j < chunk.length; j++) out.push(chunk[j] ^ keystream[j]);
counter = inc32(counter);
}
return out;
}
function getBit(bytes, i) { return (bytes[i >> 3] >> (7 - (i & 7))) & 1; } // bit 0 = MSB of byte 0
function shiftRight1(v) { // whole 16-byte value treated as one big number, shifted right 1 bit
var out = new Array(16);
out[0] = v[0] >> 1;
for (var i = 1; i < 16; i++) out[i] = (v[i] >> 1) | ((v[i-1] & 1) << 7);
return out;
}
function gmul128(x, y) { // carry-less multiply in GF(2^128), reduced mod x^128+x^7+x^2+x+1
var z = new Array(16).fill(0), v = y.slice();
for (var i = 0; i < 128; i++) {
if (getBit(x, i)) z = xorBlock(z, v);
var lsb = v[15] & 1;
v = shiftRight1(v);
if (lsb) v[0] ^= 0xe1; // R = 11100001 || 0^120, the field's own fixed reduction constant
}
return z;
}
function padTo16(bytes) { // zero-pad up to the next 16-byte boundary (0 bytes stays empty)
var out = bytes.slice();
while (out.length % 16 !== 0 && out.length > 0) out.push(0);
return out;
}
function toBlocks(bytes) {
var blocks = [];
for (var i = 0; i < bytes.length; i += 16) blocks.push(bytes.slice(i, i + 16));
return blocks;
}
function pkcs7Pad(bytes) { // always adds 1-16 bytes, never 0 — a block-aligned input gets a full block
var padLen = 16 - (bytes.length % 16);
var out = bytes.slice();
for (var i = 0; i < padLen; i++) out.push(padLen);
return out;
}
function pkcs7Unpad(bytes) { // returns null on invalid padding instead of guessing
var padLen = bytes[bytes.length - 1];
if (padLen < 1 || padLen > 16 || padLen > bytes.length) return null;
for (var i = bytes.length - padLen; i < bytes.length; i++) {
if (bytes[i] !== padLen) return null;
}
return bytes.slice(0, bytes.length - padLen);
}
function len64(bitCount) { // 8-byte big-endian bit length, as GHASH's own trailing block needs
var out = new Array(8), n = bitCount;
for (var i = 7; i >= 0; i--) { out[i] = n & 0xff; n = Math.floor(n / 256); }
return out;
}
function ghash(h, aad, ciphertext) { // authenticates aad + ciphertext under subkey h = E(key, 0^128)
var lenBlock = len64(aad.length * 8).concat(len64(ciphertext.length * 8));
var blocks = toBlocks(padTo16(aad)).concat(toBlocks(padTo16(ciphertext)), [lenBlock]);
var y = new Array(16).fill(0);
for (var i = 0; i < blocks.length; i++) y = gmul128(xorBlock(y, blocks[i]), h);
return y;
}
function gcmEncrypt(key, nonce, plaintext, aad) { // nonce: 12 bytes
var h = aes128Encrypt(new Array(16).fill(0), key);
var j0 = nonce.concat([0,0,0,1]);
var ciphertext = gctr(key, inc32(j0), plaintext);
var tag = xorBlock(ghash(h, aad, ciphertext), aes128Encrypt(j0, key));
return { ciphertext: ciphertext, tag: tag };
}
function gcmDecrypt(key, nonce, ciphertext, tag, aad) { // returns plaintext only if the tag verifies
var h = aes128Encrypt(new Array(16).fill(0), key);
var j0 = nonce.concat([0,0,0,1]);
var expectedTag = xorBlock(ghash(h, aad, ciphertext), aes128Encrypt(j0, key));
var valid = expectedTag.every(function (b, i) { return b === tag[i]; });
return { plaintext: valid ? gctr(key, inc32(j0), ciphertext) : null, valid: valid };
}
Verified against the official FIPS-197 Appendix B test vector (key
000102030405060708090a0b0c0d0e0f, plaintext
00112233445566778899aabbccddeeff) before anything else: this page's own
aes128Encrypt produces exactly the published ciphertext
69c4e0d86a7b0430d8cdb78070b4c55a, and its own aes128Decrypt recovers the exact
plaintext from it. Beyond the single known vector, fuzzed against Node's own native
crypto.createCipheriv('aes-128-ecb', key, null)/createDecipheriv (padding
disabled, so both sides operate on raw 16-byte blocks) across 5,000 random key/plaintext pairs in plain
Node — 0 mismatches either direction. A deliberately broken decrypt (round key order correct, but with
invMixColumns dropped from the loop) was run against the same harness to confirm the test
actually detects a real error: it failed on all 200 of 200 trials, not a coincidental pass. The live
ECB button above runs the identical aes128Encrypt twice, once per 16-byte half
of whatever is in that box, with no chaining between the two calls — exactly ECB, nothing more.
aesCbcEncrypt/aesCbcDecrypt were verified the same way, in the same order:
first against the official NIST SP 800-38A §F.2.1/F.2.2 AES-128-CBC test vector (key
2b7e151628aed2a6abf7158809cf4f3c, IV 000102030405060708090a0b0c0d0e0f, the
standard's own 4-block plaintext) — exact match on all four ciphertext blocks, and
aesCbcDecrypt recovers the exact plaintext from them. Then fuzzed against Node's own native
crypto.createCipheriv('aes-128-cbc', key, iv) with padding disabled, across 2,000 random
trials of 1-5 blocks each — 0 mismatches either direction. A deliberately broken encrypt (every block
XORed with the IV directly, never with the previous block's own ciphertext — i.e. CBC's first block
only, repeated) was run against the same harness to confirm it actually detects a real error: all 200 of
200 trials diverged from the correct output starting at the second block, not a coincidental pass. The
live CBC button above runs this exact chain, so the ECB demo's two identical plaintext
blocks finally produce two different ciphertext blocks.
aesCtrCrypt was verified against the official NIST SP 800-38A §F.5.1/F.5.2
AES-128-CTR test vector (same key as the CBC vector above, initial counter block
f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff, the standard's own 4-block plaintext) — exact match on all
four ciphertext blocks, and running aesCtrCrypt a second time over that ciphertext with the
same initial counter block recovers the exact original plaintext, confirming it really is the same
function both ways rather than one that happens to look symmetric. Then fuzzed against Node's own native
crypto.createCipheriv('aes-128-ctr', key, icb) across 3,000 random trials of 1–5 blocks each
— 0 mismatches. A deliberately broken counter increment (bumps only the last byte, never carries into
the byte before it on overflow) was run against the same harness, forcing the overflow case on every
trial, to confirm it actually detects a real error: all 200 of 200 trials diverged, not a coincidental
pass. The live CTR button above runs this exact function, so the ECB demo's two identical
plaintext blocks once again produce two different ciphertext blocks — by a completely different
mechanism than CBC's chaining.
gcmEncrypt/gcmDecrypt were verified against Node's own native
crypto.createCipheriv('aes-128-gcm', ...)/createDecipheriv, starting from the
four canonical all-zero-key NIST SP 800-38D test-case inputs (empty plaintext; one
all-zero block; the standard's own 4-block plaintext under a real key and nonce, with and without 20
bytes of associated data) — this page's own gcmEncrypt matched Node's ciphertext and tag
exactly on all four, and the subkey H = E(key, 0¹²⁸) computed along the way matched the
well-known published value for an all-zero key independently. Then fuzzed across 3,000 random trials
with plaintext and associated-data lengths from 0 to 69 bytes (deliberately spanning empty, partial-block,
and multi-block inputs, not just round 16-byte multiples) — 0 mismatches on ciphertext or tag either
direction, and gcmDecrypt recovered the exact original plaintext with
valid: true on every trial. A separate 500-trial tamper fuzz flipped one random ciphertext
bit per trial and confirmed gcmDecrypt reported valid: false with no plaintext
returned on all 500 — the integrity check this page's own CBC/CTR above don't have. A deliberately broken
GHASH (the trailing bit-length block silently dropped) was run against the same harness to
confirm it actually detects a real error: all 200 of 200 trials produced a tag that diverged from Node's
own, not a coincidental pass. The live Encrypt + authenticate button above runs this exact
gcmEncrypt, and the two Decrypt + verify buttons run this exact
gcmDecrypt — one on the real ciphertext, one on a bit-flipped copy.
ECB leaks the plaintext's own structure, demonstrated live above rather than only asserted. Two identical 16-byte blocks, encrypted independently under the same key, always produce the identical 16-byte ciphertext — there is no diffusion across block boundaries at all, because ECB mode is the two single-block calls above and nothing else. Edit either half of the message in the ECB demo and only that block's own ciphertext changes; the other is completely unaffected, which is itself a second leak (an attacker who can make small, repeated edits learns exactly which block changed). CBC and CTR, demonstrated live right below the ECB demo, each close exactly this leak by a different mechanism — the same two identical plaintext blocks now produce two different ciphertexts either way, because CBC's block B encryption input depends on block A's own ciphertext (not just block B's own plaintext), and CTR's two keystream blocks come from two different counter values (not just one reused encryption of the same input). Neither CBC nor CTR provides any integrity check at all, though — a tampered ciphertext decrypts to a different message instead of failing, with nothing in either mode itself to detect the tamper, and the two modes fail differently: flipping a ciphertext bit under CBC silently flips the corresponding bit of the next block's recovered plaintext, while flipping a ciphertext bit under CTR flips that exact same bit position, in the same block, and nowhere else — CTR's XOR-with-keystream structure gives an attacker a precise, single-bit-targeted edit with no side effects on neighboring bits at all, an even easier forgery primitive than CBC's one-block spillover. CTR has its own distinct failure mode neither ECB nor CBC has: reusing the same (key, initial-counter-block) pair for two different messages reproduces the identical keystream for both, so XORing the two ciphertexts together cancels the keystream out entirely and leaves exactly the XOR of the two plaintexts (a "two-time pad") — unlike CBC's IV, where reuse only risks leaking whether two messages share a common prefix, CTR counter reuse leaks a direct algebraic relationship between the two plaintexts' bytes. GCM is the standard answer to the missing-integrity gap, demonstrated live in the fourth demo above: it runs CTR mode exactly as built here for encryption, then computes a separate authentication tag over the ciphertext (and any associated data) so a tampered message fails an explicit check instead of silently decrypting wrong — closing the last piece of the original "no chaining mode" gap, now that ECB's structural leak and all three of CBC/CTR/GCM's own distinct ways of closing it are built and demonstrated live.
GCM's own nonce-reuse failure is worse than CTR's, not just the same risk restated.
Reusing a (key, nonce) pair under plain CTR leaks a two-time pad between the two messages, as above — bad,
but limited to those two messages. Reusing a (key, nonce) pair under GCM additionally hands an attacker two
GHASH outputs computed with the identical, unknown subkey H over data the attacker fully
controls one side of; subtracting them cancels everything except a linear relationship in H
itself, and H is fixed for the entire lifetime of the key — not just that one pair of
messages. Recovering H this way (the published "forbidden attack") lets an attacker forge a
valid authentication tag for any future message under that same key, no decryption or factoring
required, the one AES mode on this page where a nonce-reuse mistake compromises every message the key will
ever protect, not only the colliding pair. This page's inc32 is never tested anywhere
near the regime where it would matter. At 2³² blocks (64 GiB) per nonce, inc32's own
wraparound back to an already-used counter value is the realistic way this failure mode would actually
trigger in production — this page's demo, like the fuzz harness above, only ever encrypts a handful of
16-byte blocks per run, so the wraparound case itself is asserted from the spec, not exercised live.
Truncating the tag trades security for size, and shouldn't be done casually. This page
always uses the full 128-bit tag; the standard permits shorter tags (down to 32 bits) for applications
tight on space, at a direct, computable cost — a t-bit tag lets a forgery succeed by blind
guessing with probability roughly 2⁻ᵗ per attempt, so a 32-bit tag can be brute-forced in
around four billion tries, plausible for an online attacker against a service that doesn't rate-limit
failed verifications, where a 128-bit tag is not.
A fixed round count removes one leak class, not every leak class. AES's own round
count and instruction sequence are the same for every key and every plaintext — unlike the
square-and-multiply loop this site's Modular
Exponentiation and seven pages built on top of it reuse, there's no data-dependent branch or
early-exit anywhere in aes128Encrypt above (see Constant-Time vs. Data-Dependent Execution for
that whole category). But this page's own SubBytes is a plain array lookup,
SBOX[byte], where byte is secret-dependent data — the memory address touched
depends on a value an attacker isn't supposed to learn, even though the number of lookups never
changes. Real cache-timing attacks (Bernstein, 2005; Osvik, Shamir, and Tromer, 2006) have recovered AES
keys on shared hardware by measuring which cache lines a table-lookup S-box touches during encryption —
a side channel that survives a perfectly fixed-shape instruction sequence. Production AES either runs on
dedicated hardware instructions (AES-NI) that never touch a secret-indexed table in memory at all, or
uses a "bitsliced" software implementation that computes the S-box with pure logic operations instead
of a lookup — neither built here.
This page only builds the 128-bit-key, 10-round variant. AES-192 and AES-256 use
longer keys (192 and 256 bits), more words carried through the key schedule, and 12 or 14 rounds
respectively instead of 10 — more rounds specifically to keep the security margin proportional to the
larger key, not because a longer key alone would otherwise be unsafe at 10 rounds. All three variants
share the exact same round structure, S-box, and MixColumns matrix described above.
The Try-it demos above use a teaching shortcut, not a real padding scheme. Trailing
spaces can't be told apart from spaces the original message actually ended with, and the scheme has
nothing to say about non-text (binary) input at all. Real implementations use PKCS#7:
pad with N bytes, each one equal to N itself (N from 1 to 16, so
a message that's already block-aligned still gets a full 16 bytes of padding, 0x10
repeated) — unambiguous, self-describing, and the length of padding to strip is read directly off the
last decrypted byte. pkcs7Pad/pkcs7Unpad below build exactly that, wired into
aesCbcEncrypt/aesCbcDecrypt from the CBC demo above so any message length — not
just one or two fixed 16-byte blocks — round-trips under real CBC. The default message below ends in
real trailing spaces on purpose, to show the one thing the space-pad shortcut above structurally cannot:
Time: O(1) per 16-byte block for AES-128 — a fixed 10 rounds,
independent of the key's or plaintext's value. Every encryption performs exactly 160
SubBytes lookups (16 bytes × 10 rounds), 32 MixColumns finite-field
multiplications per round for 9 rounds (288 total — round 10 has none), and 11
AddRoundKey passes, plus 40 more SubBytes lookups inside key expansion (one
SubWord, 4 bytes, per round-key group after the first) — the exact same count for every
message encrypted under a given variant, the fixed-shape property Constant-Time vs. Data-Dependent Execution
measures directly for other algorithms on this site. aesCbcEncrypt/aesCbcDecrypt
and aesCtrCrypt above both cost exactly the same per block as ECB — O(1) per 16
bytes, same fixed work, same round count. CBC's chaining is one 16-byte XOR per block, negligible next to
the block cipher call it wraps; CBC's only extra cost sitewide is the one 16-byte IV generated and carried
per message, not per block. CTR's own extra cost is the same shape — one 16-byte XOR with the keystream
per block — plus one 16-byte increment, also negligible next to the block cipher call that produces the
keystream in the first place; CTR's only extra cost sitewide is the one 16-byte initial counter block
generated and carried per message, exactly like CBC's IV. Unlike CBC, every one of CTR's block-cipher
calls is independent of every other — aesCtrCrypt could in principle encrypt all of a
message's keystream blocks in parallel (CBC encryption cannot, since each block's input depends on the
previous block's output; CBC decryption can, since every input is already-known ciphertext), though this
page's own loop runs them sequentially either way. gcmEncrypt/gcmDecrypt cost
exactly aesCtrCrypt's own time plus one GHASH pass: one gmul128 call
— itself a fixed 128 iterations, O(1) — per 16-byte block of associated data, ciphertext, and
one trailing length block, plus exactly one more block-cipher call (encrypting J0 for the
tag) than aesCtrCrypt needed on its own. Not zero extra work the way CBC/CTR's own chaining
overhead is negligible next to a block-cipher call — gmul128's 128-iteration loop is real,
measurable cost per block, just still O(1) per block and dwarfed by aes128Encrypt's
own ~200 S-box lookups and finite-field multiplications for any message long enough to matter.
Space: O(1) — a 16-byte state and a 176-byte expanded key schedule (44
words), regardless of message length; a longer message costs one more block's worth of this same fixed
work per 16 bytes, not more per byte already processed. ECB and CBC both require the message length be an
exact multiple of 16 bytes at the block-cipher layer — that's exactly what the real PKCS#7 padding built
in Pitfalls exists to supply, at a fixed O(1) cost of its own (1 to 16 extra bytes, never
more than one extra block, regardless of message length). CTR and GCM don't share that restriction:
gctr above XORs a final partial block against only its own length of keystream, no padding
at all — this page's own CTR demo still only ever feeds it full 16-byte blocks like the ECB/CBC demos in
Try it, but the GCM demo above does feed it genuinely arbitrary-length messages,
the first demo on this page that isn't block-aligned. Security: unlike every
trapdoor-based entry on this site (RSA Encryption's
factoring, Diffie–Hellman's discrete log), AES
rests on no believed-hard mathematical problem at all — the same structural shape as SHA-256's own Complexity section describes, just for a keyed cipher
instead of a hash: its security is the absence, so far, of any attack faster than exhausting the
128-bit key space. The best published attacks (biclique cryptanalysis) shave only a small constant
factor off that exhaustive search — roughly 2^126.1 operations instead of
2^128 for AES-128 — nowhere near making brute force practical. GCM's own authentication
security is a separate, additive bound on top of that: forging a valid 128-bit tag without the key costs
roughly 2^128 guesses in the same way breaking the cipher itself does, but a deployment that
truncates the tag (see Pitfalls) trades directly down from that bound to roughly 2 raised to
the truncated tag's own bit length.