Symmetric Encryption and Block Ciphers Questions
How symmetric-key primitives are constructed and why they work: block-cipher internals (Feistel networks vs substitution-permutation networks, the AES round structure and S-box design, key schedules and why a weak one degrades security), stream ciphers (ChaCha20 and CTR-mode keystream generation), and the internal mechanics of modes of operation (ECB, CBC, CTR, XTS, GCM), including why some are parallelizable, why ECB leaks structure, and why some require a unique nonce. Covers authenticated encryption construction internals (how GHASH and Poly1305 work, why nonce reuse breaks their security algebraically, formal security notions like IND-CPA and INT-CTXT), padding schemes and the mechanics of padding-oracle attacks, and cryptanalysis of block ciphers (differential and linear cryptanalysis, reduced-round attacks). This is the design and internals layer: how these primitives are built and proven secure, distinct from choosing which algorithm or mode to deploy, managing key lifecycle and rotation, or architecting data protection for a system, which belong to the applied cryptography layer.
A protocol constructs a 96-bit nonce as 32-bit timestamp || 64-bit counter and uses AES-GCM. Describe an attacker strategy exploiting counter wraparound, clock rollback, or cloned devices, and show how nonce reuse might occur in practice. Propose a robust nonce construction and server-side checks to prevent exploitation.
Sample Answer
Direct answer
A 96-bit nonce built as a 32-bit timestamp concatenated with a 64-bit per-device counter looks unique on paper, but an attacker (or just unlucky operational conditions) can force the SAME nonce to occur twice through counter wraparound within one timestamp second, a clock rollback that revisits a (timestamp, counter) pair already used, or two cloned devices that share the same epoch and counter state; any of these collapses to full AES-GCM (Galois/Counter Mode) nonce reuse, with the usual plaintext-recovery and forgery consequences. The fix is a nonce construction where at least one component is a durable, non-resettable, globally unique value, backed by server-side replay detection.
Structured elaboration
Attack path 1: counter wraparound within one timestamp second. If a device sends messages fast enough (or the counter starts near its maximum for any reason: overflow bugs, a manipulated starting value), the 64-bit counter can wrap back to 0 while the timestamp second has not yet advanced, producing an EXACT nonce repeat within that second.
Attack path 2: clock rollback. If the device's clock can be set backward (NTP correction, battery removal, or a compromised real-time clock) AND the counter is reset alongside it (a reboot that also zeroes the counter), the device can revisit an EXACT (timestamp, counter) pair it already used before the rollback, producing a genuine nonce collision, not just a theoretical one.
Attack path 3: cloned devices. Two devices provisioned from the same firmware image, sharing the same starting epoch and the same counter-reset behavior, will independently produce IDENTICAL nonce sequences if their clocks and counters happen to align, which is common right after a factory reset or a fleet-wide provisioning event.
A robust nonce construction. Combine a device-UNIQUE identifier with a MONOTONIC, non-resettable sequence number, persisted in non-volatile storage so it survives power loss and reboots: for example, nonce = device_id (32 bits) || monotonic_counter (32 bits) || per-message random salt (32 bits), where the monotonic counter is guaranteed (by the device's own storage and boot logic) to never repeat, and the device ID prevents two cloned devices from colliding even if their counters somehow do align.
Server-side checks. The server should track the HIGHEST counter value seen per device and reject anything less than or equal to it (strict monotonic enforcement), flag and alert on any observed rollback, and treat duplicate device IDs presenting from different network sources as a signal of possible cloning requiring re-provisioning.
Worked example
The collision arithmetic made concrete, plus its consequence when fed into real AES-GCM encryption:
def build_nonce(timestamp_32, counter_64):
return (timestamp_32 & 0xffffffff).to_bytes(4, "big") + (counter_64 & 0xffffffffffffffff).to_bytes(8, "big")
ts = 0x66f3a000
n1 = build_nonce(ts, counter_64=0xFFFFFFFFFFFFFFFF)
n1_next = build_nonce(ts, counter_64=(0xFFFFFFFFFFFFFFFF + 1) % (1 << 64)) # wraps within the SAME second
print("wraparound collision:", n1_next == build_nonce(ts, 0))
ts_earlier = 0x66f39ffe
nonce_then = build_nonce(ts_earlier, counter_64=17)
nonce_after_rollback = build_nonce(ts_earlier, counter_64=17) # clock + counter both revisit the same pair
print("rollback collision:", nonce_then == nonce_after_rollback)
Output:
wraparound collision: True
rollback collision: True
Both nonce-construction failure modes produce an EXACT, reproducible nonce collision, entirely from ordinary modular arithmetic on the timestamp/counter values, with no cryptographic weakness involved: the vulnerability is in the construction, not the cipher.
Trade-offs and pitfalls
- Timestamp-based nonce components are attractive because they're "free" (no extra storage needed) but they trade that convenience for exactly this collision risk whenever the clock or counter state is not perfectly reliable, which in practice includes almost every embedded or intermittently-connected device.
- Persisting a monotonic counter durably has its own cost (flash write wear on embedded devices, for example); a common mitigation is periodically reserving a BLOCK of future counter values in storage (write the max once, use many increments before the next persisted write) so a crash between writes still cannot cause reuse, at the cost of "burning" some counter space on every restart.
- Device cloning is a provisioning-process problem, not purely a nonce-construction problem; even a perfect nonce scheme cannot fully protect a system where the SAME key material was cloned onto two devices, since a shared key is itself the deeper vulnerability there.
Describe the high-level internal structure of the Advanced Encryption Standard (AES). Cover the following in your explanation: 1) round structure including SubBytes, ShiftRows, MixColumns, AddRoundKey; 2) key schedule basics for 128/192/256-bit keys; 3) the number of rounds and how they relate to key size; 4) why AES is designed as an SPN rather than a Feistel cipher. Keep the explanation high-level (no full code required).
Sample Answer
Direct answer
The Advanced Encryption Standard (AES) is a Substitution-Permutation Network (SPN): a 128-bit data block is transformed by repeating a round made of four steps (byte substitution, row shifting, column mixing, and a key XOR), 10, 12, or 14 times depending on whether the key is 128, 192, or 256 bits. AES is built as an SPN rather than a Feistel cipher (the older DES design, where only half the block is transformed per round) because an SPN transforms the ENTIRE block every round using fully invertible, highly parallel byte-level operations, which gives strong diffusion (spreading each input bit's influence widely) in fewer rounds and maps very efficiently onto both hardware and SIMD software.
Structured elaboration
The four per-round steps.
- SubBytes: replace every byte of the state with a value from a fixed 256-entry lookup table (the S-box), a nonlinear substitution that is the ONLY source of nonlinearity in the whole cipher; without it, AES would just be linear algebra, breakable in seconds.
- ShiftRows: cyclically shift each of the state's 4 rows by a different amount (0, 1, 2, 3 byte positions), which moves bytes between the 4-byte columns that MixColumns operates on next.
- MixColumns: multiply each 4-byte column by a fixed matrix in the finite field GF(2^8) (Galois Field with 256 elements, the same algebraic structure the S-box's own construction uses), so a single changed input byte affects all 4 bytes of its column's output.
- AddRoundKey: XOR the state with that round's 128-bit round key, injecting key material.
The final round omits MixColumns (it would add no further security once the last AddRoundKey is applied, and omitting it makes decryption's inverse structure cleaner).
Number of rounds vs. key size.
| Key size | Rounds |
|---|---|
| 128-bit | 10 |
| 192-bit | 12 |
| 256-bit | 14 |
More rounds are used for larger keys to keep the security margin (the gap between the best known attack and brute force) roughly proportionate as brute-force cost grows.
Key schedule. The key schedule expands the original key into one 128-bit round key per round (11 total for AES-128, 13 for AES-192, 15 for AES-256, since round 0's AddRoundKey uses the raw key itself, plus one per round after). It operates on 32-bit words, where Nk is the key length in words (4 for a 128-bit key, 6 for 192-bit, 8 for 256-bit):
RotWord cyclically rotates a 4-byte word, SubWord applies the SAME S-box used in SubBytes to each of its 4 bytes, and Rcon is a small table of round constants that breaks symmetry between rounds (without it, a periodic pattern in the key would produce a periodic, weaker key schedule). The only structural difference across key sizes is Nk itself: a 128-bit key (Nk=4) hits the "new SubWord/RotWord/Rcon" branch every 4 words, a 192-bit key (Nk=6) every 6 words, spreading key material over MORE rounds before it repeats structurally. AES-256 (Nk=8) additionally applies one EXTRA SubWord (with no RotWord or Rcon) at the word exactly halfway between two "new" branches, adding one more nonlinear step per key-length block that 128- and 192-bit schedules do not have.
Worked example
The key schedule, run from scratch on the actual FIPS-197 published test key, so the round-key words below can be checked directly against the standard:
SBOX = [
0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16]
RCON = [0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0x1b,0x36]
def sub_word(w): return bytes(SBOX[b] for b in w)
def rot_word(w): return w[1:] + w[:1]
def key_expansion_128(key: bytes):
Nk, Nr = 4, 10
w = [key[4*i:4*i+4] for i in range(Nk)]
for i in range(Nk, 4*(Nr+1)):
temp = w[i-1]
if i % Nk == 0:
temp = bytes(a ^ b for a, b in zip(sub_word(rot_word(temp)), bytes([RCON[i//Nk - 1], 0, 0, 0])))
w.append(bytes(a ^ b for a, b in zip(w[i-Nk], temp)))
return [b"".join(w[4*r:4*r+4]) for r in range(Nr+1)]
key = bytes.fromhex("000102030405060708090a0b0c0d0e0f")
round_keys = key_expansion_128(key)
for i, rk in enumerate(round_keys):
print(f" w[{4*i:2d}..{4*i+3:2d}] = {rk.hex()}")
print("number of round keys :", len(round_keys), "(Nr+1 = 11 for AES-128)")
Output:
w[ 0.. 3] = 000102030405060708090a0b0c0d0e0f
w[ 4.. 7] = d6aa74fdd2af72fadaa678f1d6ab76fe
w[ 8..11] = b692cf0b643dbdf1be9bc5006830b3fe
w[12..15] = b6ff744ed2c2c9bf6c590cbf0469bf41
w[16..19] = 47f7f7bc95353e03f96c32bcfd058dfd
w[20..23] = 3caaa3e8a99f9deb50f3af57adf622aa
w[24..27] = 5e390f7df7a69296a7553dc10aa31f6b
w[28..31] = 14f9701ae35fe28c440adf4d4ea9c026
w[32..35] = 47438735a41c65b9e016baf4aebf7ad2
w[36..39] = 549932d1f08557681093ed9cbe2c974e
w[40..43] = 13111d7fe3944a17f307a78b4d2b30c5
number of round keys : 11 (Nr+1 = 11 for AES-128)
w[0..3] is just the original key (round 0 uses the raw key), and these are exactly the round-key words FIPS-197's own worked appendix publishes for this test key, so they can be checked directly against the standard. Feeding these round keys and the SubBytes/ShiftRows/MixColumns/AddRoundKey round function into the full cipher on FIPS-197's paired test plaintext reproduces its published ciphertext exactly, confirming the schedule and round structure are self-consistent end to end.
Trade-offs and pitfalls
- SPN vs. Feistel is a real design trade-off, not a strict "SPN wins": a Feistel round function does not need to be invertible on its own (only the whole round does, via the swap-and-XOR structure), which historically made Feistel ciphers easier to analyze and implement in constrained hardware. AES's designers judged the SPN's parallelism and stronger per-round diffusion worth the requirement that every layer (S-box, ShiftRows, MixColumns) individually be invertible.
- A common mix-up is treating "10/12/14 rounds" as if larger keys always mean proportionally more rounds; the relationship is not linear (128 to 256 bits is 2x the key length but only 1.4x the rounds), reflecting how the security margin against known attacks actually scales, not the key length itself.
- The key schedule is deterministic and public; nothing about it is secret except the original key material. Its purpose is diffusion and breaking symmetry between rounds, not adding secret entropy.
Compare Cipher Block Chaining (CBC) and Counter (CTR) modes with respect to performance and parallelizability. Explain which parts of encryption and decryption are parallelizable for each mode, how random-access reading is supported, and implications for hardware acceleration and streaming workloads.
Sample Answer
Direct answer
Cipher Block Chaining (CBC) encryption is inherently sequential (each ciphertext block depends on the previous one), while CBC decryption and Counter (CTR) mode's encryption and decryption are all independently parallelizable and randomly addressable. CTR is the better fit for hardware acceleration and streaming/random-access workloads; CBC's main advantage is that it needs no per-block counter management, at the cost of encryption-side parallelism.
Structured elaboration
CBC's dependency structure. Encryption is Ci=AESK(Pi⊕Ci−1) (with C_0 = IV, the initialization vector): computing C_i requires C_{i-1} to already exist, so encryption of a message must proceed block by block, in order. Decryption, Pi=AESK−1(Ci)⊕Ci−1, only needs the CIPHERTEXT blocks, which are all already available before decryption starts, so every block's AES-decrypt call can run in parallel; only the final XOR-with-previous-ciphertext step ties them together, and that is cheap.
CTR's dependency structure. Every block is independent in both directions: Ci=Pi⊕AESK(nonce∥i). There is no chaining at all; each block's keystream depends only on the nonce and that block's own counter value, so encryption AND decryption are both fully parallelizable, and any single block can be produced without touching any other block.
Random access. CBC decryption of block i alone needs blocks i-1 and i (not the whole prefix from block 0), so mid-stream random-read is possible but requires keeping every ciphertext block addressable by index, still tied to its immediate predecessor. CTR needs nothing but the counter value for the block you want; there is no predecessor dependency at all, which is why CTR (and AEAD modes built on it, like AES-GCM) are the standard choice for encrypted disks and random-access file formats.
Hardware and streaming implications. CTR keystream blocks can be precomputed ahead of the data arriving (since they depend only on the counter, not the plaintext), pipelined across SIMD lanes, or fanned out across cores; this maps directly onto AES-NI (hardware AES instructions) and GPU-style parallelism. CBC encryption cannot be precomputed this way because each block's input literally depends on the previous block's output, which caps encryption throughput at one block's latency times the block count for a single stream (parallelizing across MULTIPLE independent streams is still possible, just not within one).
Worked example
Decrypt block index 2 of a 4-block message DIRECTLY, using only its own dependency (no traversal from block 0), for both modes:
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
key = bytes.fromhex("000102030405060708090a0b0c0d0e0f")
iv = bytes.fromhex("0f0e0d0c0b0a09080706050403020100")
plaintext = bytes(range(64)) # 4 distinct 16-byte blocks: 00..0f, 10..1f, 20..2f, 30..3f
enc = Cipher(algorithms.AES(key), modes.CBC(iv)).encryptor()
ciphertext_cbc = enc.update(plaintext) + enc.finalize()
blocks = [ciphertext_cbc[i:i+16] for i in range(0, 64, 16)]
# CBC: P2 = AES_decrypt(C2) XOR C1, using ONLY blocks[1] and blocks[2]
raw_dec = Cipher(algorithms.AES(key), modes.ECB()).decryptor()
aes_inv_c2 = raw_dec.update(blocks[2]) + raw_dec.finalize()
p2_direct = bytes(a ^ b for a, b in zip(aes_inv_c2, blocks[1]))
print("CBC block 2 matches plaintext:", p2_direct == plaintext[32:48])
# CTR: block 2's plaintext needs only the counter value for index 2
nonce = bytes.fromhex("f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff")
enc_ctr = Cipher(algorithms.AES(key), modes.CTR(nonce)).encryptor()
ciphertext_ctr = enc_ctr.update(plaintext) + enc_ctr.finalize()
counter_for_block2 = nonce[:12] + (int.from_bytes(nonce[12:], "big") + 2).to_bytes(4, "big")
raw_enc = Cipher(algorithms.AES(key), modes.ECB()).encryptor()
keystream2 = raw_enc.update(counter_for_block2) + raw_enc.finalize()
p2_ctr_direct = bytes(a ^ b for a, b in zip(ciphertext_ctr[32:48], keystream2))
print("CTR block 2 matches plaintext:", p2_ctr_direct == plaintext[32:48])
Output:
CBC block 2 matches plaintext: True
CTR block 2 matches plaintext: True
CBC's recovery used exactly TWO ciphertext blocks (blocks[1] and blocks[2]), never touching block 0 or a full chain traversal; CTR's recovery used only the counter derived from the block index and never read any ciphertext block other than block 2 itself, no predecessor at all.
Trade-offs and pitfalls
| CBC | CTR | |
|---|---|---|
| Encryption | Sequential | Fully parallel |
| Decryption | Parallel (per block) | Fully parallel |
| Random-access read | Needs block i-1 and i | Needs only counter for block i |
| Hardware fit | Weaker on the encrypt side | Excellent both directions |
| Failure mode of a flipped ciphertext bit | Corrupts that block plus one bit in the next block's plaintext | Corrupts exactly that bit's position, nothing else |
- CBC needs an unpredictable IV per message (not merely unique); reusing or predicting IVs enabled real historical attacks against early TLS (see the BEAST attack: Browser Exploit Against SSL/TLS, which exploited TLS 1.0's predictable IVs, each record's IV was just the last ciphertext block of the previous record, to let an attacker who could inject chosen plaintext decrypt secret data one byte at a time).
- CTR needs a UNIQUE nonce/counter combination per key, never reused; reuse collapses to the same keystream-reuse failure as any stream cipher.
- Neither mode alone provides integrity; both are commonly paired with a MAC (message authentication code) or, more robustly, replaced entirely by an AEAD construction like AES-GCM, which is built on CTR internally and inherits its parallelism.
You are reviewing C code using OpenSSL EVP APIs that attempts to construct a 64-bit random prefix and a 64-bit counter to form a 128-bit IV but then passes that 16-byte IV to AES-GCM as though it were a correct nonce. Here is the snippet:
uint8_t iv[16];
memcpy(iv, random_prefix, 8);
memcpy(iv+8, &counter, 8); // counter is uint64_t
EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, key, iv);
Identify the issues with this approach (including RFC guidance about IV length for GCM), possible attacks or inefficiencies, and propose a correct and robust IV derivation and management strategy compliant with standards.
Sample Answer
Direct answer
This snippet builds a 16-byte (128-bit) IV (initialization vector, a value that must be used only once per key) for AES-GCM (Galois/Counter Mode) from an 8-byte random prefix and an 8-byte raw counter, but GCM's fast, standard path is defined specifically for a 12-byte (96-bit) IV; a 16-byte IV forces GCM to run an extra GHASH pass just to derive the internal counter block, and the raw memcpy of a uint64_t counter bakes in the host's native byte order (little-endian on most modern CPUs), which is not portable and easy to get silently wrong across machines or restarts.
Structured elaboration
Issue 1: wrong IV length for the fast path. NIST SP 800-38D (the GCM specification) and the OpenSSL EVP (envelope, OpenSSL's high-level cryptographic API) documentation both describe a 96-bit IV as the OPTIMIZED, recommended case: J0 = IV || 0x00000001, no field arithmetic needed. Any other length, including this snippet's 16 bytes, forces J0 to be derived by running GHASH over the padded IV plus a length block BEFORE encryption can even start, adding both latency and one more place for a mistake to leak information about H (the internal GHASH subkey) if the IV itself is ever attacker-influenced.
Issue 2: no explicit IV length set on the context. The snippet calls EVP_EncryptInit_ex with a 16-byte iv buffer but never calls EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, ...) to tell OpenSSL the actual IV length being used; relying on the cipher's compiled-in default risks a mismatch between what the caller intends and what OpenSSL actually consumes.
Issue 3: host-endian counter encoding. memcpy(iv+8, &counter, 8) copies the raw in-memory bytes of a uint64_t, which on a little-endian machine (the overwhelming majority of deployed hardware) produces the counter's LEAST significant byte first. This is non-portable (the same counter value produces a DIFFERENT nonce on a big-endian machine) and easy to get wrong when persisting or comparing counters across a restart, increasing the risk of an accidental nonce COLLISION, which for AES-GCM is catastrophic (see the nonce-reuse forgery/plaintext-recovery attacks on this same construction).
Issue 4: counter persistence and uniqueness are unaddressed. Nothing in the snippet shows the counter being persisted across restarts or protected from being reset to a previously used value; without that guarantee, "8-byte counter" is not actually a uniqueness guarantee.
Worked example
A corrected version: 96-bit nonce built as a 4-byte per-session salt plus an 8-byte big-endian monotonic sequence number, IV length set explicitly, full encrypt/decrypt/verify round trip, using the OpenSSL EVP API in C, compiled and run directly:
#include <openssl/evp.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>
int main(void) {
unsigned char key[16] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,
0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f};
unsigned char salt[4] = {0xaa, 0xbb, 0xcc, 0xdd}; /* per-session, unique */
uint64_t seq = 42;
unsigned char iv[12];
memcpy(iv, salt, 4);
for (int i = 0; i < 8; i++) iv[4 + i] = (unsigned char)((seq >> (56 - 8*i)) & 0xff); /* explicit big-endian */
const unsigned char plaintext[] = "authorize:acct=104291;amt=50000";
int plaintext_len = (int)strlen((const char *)plaintext);
const unsigned char aad[] = "hdr:v=3";
int aad_len = (int)strlen((const char *)aad);
unsigned char ciphertext[128], tag[16];
int len, ciphertext_len;
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 12, NULL); /* explicit, matches our 12-byte IV */
EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv);
EVP_EncryptUpdate(ctx, NULL, &len, aad, aad_len);
EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len);
ciphertext_len = len;
EVP_EncryptFinal_ex(ctx, ciphertext + len, &len);
ciphertext_len += len;
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, tag);
EVP_CIPHER_CTX_free(ctx);
unsigned char decrypted[128];
int decrypted_len;
EVP_CIPHER_CTX *dctx = EVP_CIPHER_CTX_new();
EVP_DecryptInit_ex(dctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
EVP_CIPHER_CTX_ctrl(dctx, EVP_CTRL_GCM_SET_IVLEN, 12, NULL);
EVP_DecryptInit_ex(dctx, NULL, NULL, key, iv);
EVP_DecryptUpdate(dctx, NULL, &len, aad, aad_len);
EVP_DecryptUpdate(dctx, decrypted, &len, ciphertext, ciphertext_len);
decrypted_len = len;
EVP_CIPHER_CTX_ctrl(dctx, EVP_CTRL_GCM_SET_TAG, 16, tag);
int ok = EVP_DecryptFinal_ex(dctx, decrypted + len, &len);
decrypted_len += len;
EVP_CIPHER_CTX_free(dctx);
decrypted[decrypted_len] = '\0';
printf("decrypt+verify status: %s\n", ok > 0 ? "OK (tag valid)" : "FAILED (tag invalid)");
printf("decrypted plaintext: %s\n", decrypted);
printf("round-trip matches original: %s\n",
(decrypted_len == plaintext_len && memcmp(decrypted, plaintext, plaintext_len) == 0) ? "true" : "false");
return 0;
}
Compiled with gcc iv.c -o iv -I<openssl-include> -L<openssl-lib> -lcrypto and run:
decrypt+verify status: OK (tag valid)
decrypted plaintext: authorize:acct=104291;amt=50000
round-trip matches original: true
The corrected version uses a 12-byte IV (GCM's fast path), sets the IV length on the context explicitly, and encodes the counter portion with an explicit big-endian loop rather than a raw struct memcpy, removing the endianness dependency entirely.
Trade-offs and pitfalls
- Never rely on a language's or platform's native integer byte order for anything that becomes part of a cryptographic nonce or key; always encode explicitly.
- A 4-byte salt plus an 8-byte counter is a common, sound pattern, but the salt MUST be freshly generated per key (never reused across key rotations) and the counter MUST be persisted durably (surviving process restarts) or the key must be rotated whenever the counter's persistence cannot be guaranteed.
- If the IV length genuinely cannot be constrained to 96 bits (interoperability with a fixed external format, for example), the GHASH-derived
J0path is still cryptographically sound, just slower; the real defect in the original snippet is the unmanaged counter encoding and missing explicit IV-length configuration, not merely "the IV isn't 96 bits." - Always set
EVP_CTRL_GCM_SET_IVLENexplicitly rather than relying on the library's default, since defaults can differ across OpenSSL versions and silent mismatches are hard to detect in testing.
Design a secure AEAD initialization and nonce generation strategy for an embedded device with limited entropy sources, intermittent connectivity, and power cycles. Your scheme must avoid GCM nonce reuse, limit persistent state writes (flash wear), and provide reasonable protection even if the device's RNG is weak at boot.
Sample Answer
Direct answer
Split the nonce into two parts with very different write costs: a small persisted "epoch" counter that survives power loss and is bumped rarely (so it barely touches flash), and a large in-RAM per-epoch message counter that resets to zero at each epoch and never needs to be written to non-volatile storage at all. On every boot, the device bumps the epoch by more than the worst-case number of increments it could have lost track of, which guarantees (epoch, counter) never repeats even with zero trustworthy randomness at boot. A weak boot-time random-number generator (RNG) becomes a non-issue because nothing about uniqueness depends on randomness; it depends on the epoch counter's monotonicity, which flash and a conservative boot-time bump policy provide deterministically.
Structured elaboration
Nonce format: for a 96-bit AEAD (authenticated encryption with associated data) nonce, use a 32-bit persisted epoch (flash-backed) concatenated with a 64-bit in-RAM message counter reset to zero at the start of each epoch. Both halves together are guaranteed unique as long as the epoch never repeats and the in-RAM counter never wraps within one epoch (2^64 messages per epoch is far beyond what any embedded device sends before its next power cycle or maintenance window).
Handling limited entropy at boot: many embedded devices have a weak or slow-to-warm-up RNG immediately after power-on (no keyboard/mouse jitter, limited peripherals, sometimes a deterministic boot ROM). Because uniqueness here comes from the flash-backed epoch, not from randomness, a weak boot RNG only threatens confidentiality of anything that genuinely needs fresh randomness elsewhere (like key generation during provisioning), not nonce uniqueness. If the device does have some entropy (even low-quality), mix it into the AEAD key derivation as an extra input (never as the sole nonce source), so it adds defense in depth without being load-bearing.
Limiting flash wear: the epoch value is the only thing written to flash, and only at boot, not per message. Because NOR flash (a common non-volatile flash-memory type used in embedded devices, distinct from denser NAND flash) has a guaranteed endurance typically on the order of 100,000 erase/write cycles per sector, and a real device power-cycles far less often than it sends messages, this keeps the counter well inside its wear budget for the device's whole service life, shown concretely below. A common refinement is wear-leveling the epoch counter across multiple flash sectors in rotation, but for the write volumes involved here that is usually unnecessary headroom rather than a requirement.
Recovering from an ambiguous "torn write" at boot: flash writes can be interrupted mid-write by another power loss. The standard defense is to always bump the epoch by a safety margin (for example, +4 rather than +1) on every boot, so that even if the previous epoch write was torn and the device cannot tell whether it completed, the new epoch is still guaranteed strictly greater than anything that could have been used before the crash.
Worked example
NOR_FLASH_ENDURANCE_CYCLES = 100_000 # typical guaranteed NOR flash erase/write cycles
DEVICE_LIFETIME_YEARS = 10
MESSAGES_PER_DAY = 500 # e.g. a sensor reporting every ~3 minutes
epoch_bits, counter_bits = 32, 64
messages_per_epoch = 2 ** counter_bits
total_messages_lifetime = MESSAGES_PER_DAY * 365 * DEVICE_LIFETIME_YEARS
print(f"total messages over {DEVICE_LIFETIME_YEARS}y lifetime: {total_messages_lifetime:,}")
print(f"counter space per epoch (2^{counter_bits}): {messages_per_epoch:.3e} -- never exhausted in practice")
boots_per_year_estimate = 200 # power cycles: outages, maintenance, watchdog resets
worst_case_epoch_bumps_per_boot = 4 # safety margin for a torn/ambiguous flash write
flash_writes_over_lifetime = boots_per_year_estimate * DEVICE_LIFETIME_YEARS * worst_case_epoch_bumps_per_boot
print(f"\nflash writes to the epoch counter over lifetime: {flash_writes_over_lifetime:,}")
print(f"NOR flash endurance budget: {NOR_FLASH_ENDURANCE_CYCLES:,} cycles")
print(f"headroom: {NOR_FLASH_ENDURANCE_CYCLES / flash_writes_over_lifetime:.0f}x under the endurance limit")
print(f"\n2^{epoch_bits} possible epoch values vs {flash_writes_over_lifetime:,} used over lifetime: "
f"epoch space is {2**epoch_bits / flash_writes_over_lifetime:.3e}x larger than needed")
Output:
total messages over 10y lifetime: 1,825,000
counter space per epoch (2^64): 1.845e+19 -- never exhausted in practice
flash writes to the epoch counter over lifetime: 8,000
NOR flash endurance budget: 100,000 cycles
headroom: 12x under the endurance limit
2^32 possible epoch values vs 8,000 used over lifetime: epoch space is 5.369e+05x larger than needed
Trade-offs and pitfalls
The 12x headroom over the flash endurance budget is comfortable but not enormous; a device with far more frequent power cycles than this estimate (a battery-powered sensor that browns out daily, for instance) needs the safety-margin bump reduced or the epoch made wider, and this is exactly the kind of number a design review should recompute for the real deployment rather than trusting a generic assumption. A second pitfall is conflating this scheme's guarantee (uniqueness) with confidentiality: uniqueness alone stops the classic AES-GCM (Galois/Counter Mode) two-message keystream-XOR attack, but if the device's key derivation function (KDF) genuinely depends on weak boot entropy for the KEY itself (not the nonce), that is a separate and more serious problem this nonce scheme does not solve. Finally, resist reaching for a purely random 96-bit nonce "because that's what the AEAD library expects by default": on a device with a weak or slow RNG at boot, a random nonce is exactly the design that silently degrades into a collision risk, which is the failure mode this whole question is about avoiding.
Unlock Full Question Bank
Get access to all 21 Symmetric Encryption and Block Ciphers interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.