292 local laboratory notebooks. Download the file, then upload it to Colab.
292 results
Primary course experiments · 237
CR01 · Primary · Cryptography Engineering
CR01 · Feistel · two-round worked example
Split a 32-bit word into 16-bit halves. Lᵢ₊₁=Rᵢ; Rᵢ₊₁=Lᵢ XOR F(Rᵢ,Kᵢ). F is K XOR ROTL16(R,4). Rotation wraps discarded bits; XOR is carry-free. Swap final halves to encrypt; reverse keys to decrypt. The final swap and reverse-key recovery verify the calculation.
Confusion complicates the key-to-ciphertext relationship; diffusion spreads plaintext changes. A Hamming distance counts differing bits. This linear toy F cannot provide modern security even if more rounds are used.
CR03 · DES · permutations and complete round trace
DES consumes 64-bit blocks; PC-1 removes eight parity bits from the supplied 64-bit key. IP rearranges bits; E expands 32 to 48 bits; XOR with K, eight S-boxes compress to 32 bits; P permutes; 16 Feistel rounds, swap and IP inverse finish encryption. DES is historical only.
Each 6-bit input b₁…b₆ maps to four output bits. Row = 2b₁+b₆; column = binary b₂…b₅. The eight boxes differ. A nonlinear substitution is not a permutation of all 64 inputs.
PC-1 selects 56 key bits into C₀,D₀ (28 bits each). Rotations use schedule 1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1. PC-2 selects 48 bits. Flipping the least significant bit of each supplied byte changes parity only.
CR06 · DES · plaintext and effective-key avalanche
Compute d=popcount(A XOR B); report 100d/64. Compare corresponding L||R after IP and each round. In separate trials flip one plaintext bit and one key bit; bit 0 in the supplied key is parity, bit 1 is effective.
Double DES uses E₂(E₁(P)); two-key TDEA uses E₁(D₂(E₁(P))) and three-key TDEA uses E₃(D₂(E₁(P))). Decryption reverses order and operation. Key-length arithmetic is not effective security; TDEA was withdrawn by NIST in 2024.
A known synthetic pair can be matched by storing E₁(P) for a tiny keyspace, then comparing D₂(C). Time and memory trade off. This is a deliberately non-DES 8-bit toy permutation E(x,k)=(x+17k) mod 256, for 16 possible keys. Collisions illustrate why another pair is needed (this toy may still collide).
GF(2) has coefficients 0 and 1; add/subtract modulo 2, so identical terms cancel. A bit string represents a polynomial; 2³=8 is ordinary arithmetic, while GF(2³) has eight elements but is not integers modulo 8.
CR10 · GF(2³) · multiplication, reduction and inverse
m(x)=x³+x+1 (0xB). Multiply by shift-and-XOR, divide raw product by m(x), keep remainder. Every nonzero element has an inverse. For example, 3×5→4, the inverse(3)=6, field division 7/3→4.
AES uses m(x)=x⁸+x⁴+x³+x+1 (0x11B). For example, 0x57 XOR 0x83=0xD4. Also, xtime(57)=AE and xtime(AE)=47. The extended Euclidean algorithm uses polynomial quotient and XOR to find the inverse.
AES operates on a single 128-bit block arranged as four columns of four bytes. The first four serialized bytes occupy column 0, not row 0. A round key is always 16 bytes. The original key has Nk=4, 6 or 8 words, so Nr=Nk+6; the expansion provides Nr+1 round keys. The first AddRoundKey is outside the Nr standard rounds. s[r,c] = input[4c+r]; Nr = Nk + 6; s′[r,c] = s[r,c] XOR k[r,c]. Byte index 6 is row 2, column 1. For baseline byte 6: 66 XOR 06 = 60.
SubBytes maps each byte independently through a fixed public nonlinear bijection. For nonzero a, find its multiplicative inverse under the AES field polynomial 0x11B. For a=0 use the special inverse input zero, not a mathematical inverse. Apply the affine transformation: XOR the inverse and its 1-, 2-, 3-, 4-bit left rotations, then XOR 0x63. The lookup row and column are high and low nibbles. 53⁻¹ = CA in GF(2⁸); CA ⊕ 95 ⊕ 2B ⊕ 56 ⊕ AC ⊕ 63 = ED. The inverse S-box maps ED to 53.
ShiftRows changes positions rather than values. For output at row r, column c, the forward source is row r, column (c+r) mod 4. InvShiftRows uses (c−r) mod 4. Row 0 is unchanged, and row 3 rotates left by three, equivalent to right by one. This sends bytes from an original column into different columns before MixColumns. For the baseline row 2: 02 06 0A 0E → 0A 0E 02 06. Byte 0E moves from row 2, column 3 to row 2, column 1.
MixColumns transforms each four-byte column independently using a fixed 4×4 circulant matrix. Field multiplication is polynomial multiplication with XOR and modular reduction by 0x11B; multiplying by 02 is xtime and by 03 is xtime XOR the original byte. The inverse matrix has first row 0E 0B 0D 09. The forward and inverse matrices multiply to the identity over the field. For column DB 13 53 45, row 0: (02·DB) ⊕ (03·13) ⊕ 53 ⊕ 45 = AD ⊕ 35 ⊕ 53 ⊕ 45 = 8E. Other rows yield 4D A1 BC.
AddRoundKey combines the current state with a 16-byte round key by XOR. A 192- or 256-bit original AES key still yields 128-bit round keys through key expansion. XOR is its own inverse; changing one key bit changes the corresponding output bit at this stage, unlike subsequent diffusion across a full cipher. Byte index 1: 0x11 = 00010001; 0x01 = 00000001; XOR = 00010000 = 0x10. Applying 01 again restores 11.
Split the supplied key into four-byte words. For i≥Nk, start temp=w[i−1]. If i mod Nk=0, rotate by one byte, substitute each byte and XOR the appropriate Rcon word. If Nk=8 and i mod Nk=4, substitute without rotation or Rcon. Otherwise temp is unchanged. Compute w[i]=w[i−Nk] XOR temp. Each four consecutive words forms a round key. For AES-128: w[3]=0C0D0E0F → RotWord=0D0E0F0C → SubWord=D7AB76FE → XOR 01000000=D6AB76FE; w[4]=00010203 XOR D6AB76FE=D6AA74FD.
Encryption begins with AddRoundKey, then repeats SubBytes, ShiftRows, MixColumns and AddRoundKey. The last round omits MixColumns. Decryption starts with the final round key and reverses the operations: InvShiftRows, InvSubBytes, AddRoundKey, then InvMixColumns except at the end. Round states are column-major byte sequences. This is a raw single-block primitive, not an authenticated message-encryption system. Known-answer vector: plaintext 00112233445566778899AABBCCDDEEFF with key 000102030405060708090A0B0C0D0E0F yields 69C4E0D86A7B0430D8CDB78070B4C55A.
Hamming distance counts set bits in XOR of two equally sized states. Normalize by the 128-bit state width, not the key length. Compare identical AddRoundKey boundaries in baseline, plaintext-only and key-only runs. Bit numbering here starts at bit 0 of the last byte, so bit 120 is the low bit of the first byte for a 16-byte block. Diffusion generally spreads differences, but the distance need not grow monotonically and one trial cannot prove security. At bit 120 the reference final distances are 58/128=45.3125% (plaintext) and 53/128=41.40625% (key). At round 1 the counts are 20 and 22.
ECB applies AES independently to every 16-byte block. Identical plaintext under the same key yields identical ciphertext; encryption does not hide equality. ECB has no IV and requires complete blocks or separately applied padding. It provides no authentication. A ciphertext bit error may corrupt many bits in its own plaintext block, but does not propagate to other blocks. The three repeated 6BC1…172A blocks under key 2B7E…4F3C each encrypt to 3AD77BB40D7A3660A89ECAF32466EF97. The identical tile colors in the model represent equality, not actual image pixels.
CBC XORs Pᵢ with Cᵢ₋₁ before encryption; C₀ is the IV. During decryption, decrypt Cᵢ and XOR with the previous ciphertext. The IV must be unpredictable and protected against unauthorized modification. CBC requires full blocks or padding. Flipping a ciphertext bit can corrupt the corresponding plaintext block and flips the same bit in the next plaintext block, if present. For block 1, 6B XOR 00 = 6B and C1 XOR 01 = C0 (second byte of P₁). With the supplied IV, C₁ = 7649ABAC8119B246CEE98E9B12E9197D.
CFB encrypts a 128-bit feedback register and XORs the leading s bytes of its output with input. Both encryption and decryption use the AES encryption primitive; append ciphertext, not plaintext, to the shifted register. The segment length s is in bytes here (1–16). CFB does not require block padding and its IV must be unpredictable. The first AES output for the baseline IV is 50FE67CC996D32B6DA0937E99BAFEC60; first byte 6B XOR 50 = 3B. In CFB-8 only 3B is appended to the shifted register on that step.
OFB encrypts the feedback state to obtain the next state and keystream. The stream is XORed with either plaintext or ciphertext. Ciphertext never feeds back into the state. With a fixed key, IVs must not be reused. A ciphertext bit flip causes a corresponding single plaintext bit flip. Baseline first output state is 50FE67CC996D32B6DA0937E99BAFEC60; P₁ XOR this state gives 3B3FD92EB72DAD20333449F8E83CFB4A.
CTR encrypts successive distinct 128-bit counter blocks and XORs the result with data. This lab increments the entire counter as a big-endian integer. Every counter block must be unique under a given key, across all messages. The final short block uses only the needed stream bytes; encryption and decryption can process independent blocks. Baseline counter ends in 0E0F; increment gives 0E10. First output is 50FE…EC60, so first ciphertext byte is 6B XOR 50 = 3B.
Use the same AES primitive, key, complete-block message and test IV/counter for each mode. This is a controlled structural experiment, not a timing benchmark. ECB reveals equality; CBC chains ciphertext; CFB feeds ciphertext; OFB feeds cipher output; CTR increments a counter. These modes do not authenticate ciphertext. The chosen IV is for reproducibility, not a deployment recommendation. With three repeated blocks, only ECB is expected to preserve adjacent block equality for this reference. A first-block bit flip affects CBC blocks 1–2, CFB-128 blocks 1–2, and only the corresponding bit in OFB/CTR.
CR27 · XTS-AES · sector tweaks and ciphertext stealing
XTS uses two separate AES keys. T₀ = E(K₂, little-endian sector identifier), and successive tweaks multiply by α in GF(2¹²⁸). A full block is transformed by C = E(K₁,P XOR T) XOR T. For a short final block, ciphertext stealing rearranges bytes from the provisional penultimate block so the sector length is preserved. Decryption reverses these operations. XTS provides storage confidentiality, not message authentication. The 21-byte baseline yields a 16-byte full ciphertext and a 5-byte short ciphertext. Sector 7 produces first tweak F7D73FDACC0B64382D81CF8EDC9C338A.
CR28 · Block ciphers · architecture and fair comparison
DES (64/56/16), TDEA (64/112 or 168 nominal/48 DES rounds), AES (128/128–256/10–14), Blowfish (64/32–448/16), Twofish (128/128–256/16). Compare structure and effective limitations; benchmark same backend and workload only. Historical algorithms are not recommendations.
CR29 · Randomness · statistical appearance and predictability
The empirical one-bit entropy H=−p log₂p−(1−p)log₂(1−p) uses only marginal frequencies. Runs count contiguous groups of equal bits. Adjacent-match fraction is the number of equal adjacent pairs divided by N−1. A balanced deterministic pattern can have H=1 but remain completely predictable. 0101 repeated eight times contains 8 zeros, 8 ones, 16 runs, H=1 and adjacent-match fraction 0.
LCG uses Xₙ₊₁=(aXₙ+c) mod m. The state is the residue, not just the displayed output. The eventual cycle length is counted after repeated-state detection, independent of the requested output count. A sequence may have a transient before its cycle. LCG is predictable and unsuitable for security. Seed 3, a=5, c=1, m=16: X₁=(5×3+1) mod 16=0, X₂=1. The default eventual cycle has length 16.
BBS selects distinct primes p,q congruent to 3 modulo 4, a seed coprime to n=pq, and initializes x₀=s² mod n. Each iteration squares the current state modulo n and outputs its least significant bit. Small public classroom parameters provide no real security. p=7, q=11, s=5 gives n=77, x₀=25, x₁=25² mod77=9, output bit 1; x₂=81 mod77=4, output 0.
CR32 · AES-OFB and CTR · deterministic bit generation
This experiment compares two deterministic AES stream constructions with an explicit initial state, fixed key and zero input. OFB updates V to E(K,V), while CTR emits E(K,V) then increments V. These are educational deterministic generators, not standardized DRBGs with approved instantiate, update and reseed procedures. For the sequential baseline key and state, both first output blocks are 0A940BB5416EF045F1C39458C653EA5A. Their second input states differ.
CR34 · Entropy · bias, conditioning and OS randomness
Von Neumann conditioning consumes nonoverlapping pairs: equal bits 00/11 are discarded; 01 maps to 0 and 10 maps to 1. Under independent identically distributed biased input the accepted bits are unbiased; correlated input can violate this assumption. An odd trailing bit is not processed. Empirical entropy is not a source assessment. OS randomness is obtained from the operating system, not from this synthetic sequence. For 00 01 10 11, discard 00 and 11, output 01. An alternating 01 sequence yields all zeros despite balanced input.
RC4 begins with S=[0,…,255]. KSA updates j using S[i] and a repeating key byte, then swaps entries. PRGA updates i and j, swaps again and selects t=(S[i]+S[j]) mod 256; z=S[t], output=P XOR z. It is obsolete and must not be used for new security systems. With key 0102030405, KSA step 0 sets j=1 and swaps S[0],S[1]. The first 16 PRGA bytes for zero plaintext are B2396305F03DC027CCC3524A0A1118A8 (RFC 6229).
For positive modulus n, a=qn+r with 0≤r<n. Congruence means equal residues, not equal integers. On the GF(17) clock, 35→1, −7→10 and −11→6. Addition and multiplication reduce after the operation.
A field has additive and multiplicative identities and every nonzero element has a multiplicative inverse. Modulo a composite integer, zero divisors can exist; GF(pⁿ) is not ordinary integer arithmetic modulo pⁿ.
An inverse x satisfies ax≡1 mod n. Division a/b means a·b⁻¹, defined only when gcd(b,n)=1. The lecture includes 421 mod 1009 and 10 mod 40 (no inverse).
Forward division finds gcd; back-substitution rewrites it as ax+ny. Reduce x modulo n to obtain the inverse if gcd=1. Worked example: 20⁻¹ mod 23 = 15.
The order of g is the first positive exponent giving 1. A primitive root modulo prime p has order p−1. Inversion of exponentiation is the discrete-logarithm problem.
For distinct odd primes p and q, n=pq and φ(n)=(p−1)(q−1). Choose 1<e<φ(n) with gcd(e,φ)=1. The extended Euclidean algorithm finds d such that e·d≡1 mod φ. Small classroom primes are not secure. p=5, q=11, e=3: n=55, φ=40, 40=13·3+1, so 1=40−13·3 and d=−13 mod 40=27. Verify 3·27 mod 40=1.
Textbook RSA maps 0≤m<n to c=mᵉ mod n and recovers cᵈ mod n. Square-and-multiply uses exponent bits and reduces after every multiplication or squaring. Raw RSA is deterministic and unsafe for production encryption. n=55,e=3,d=27,m=7: c=343 mod 55=13. For 13²⁷ use powers 1,2,8,16 (27=16+8+2+1); result=7.
Each UTF-8 byte must be less than n. CRT decrypts modulo p and q and reconstructs the unique residue modulo n using modular inverses. Reduced private exponents accelerate operations. Repeated plaintext bytes reveal equality in raw RSA. p=11,q=13,e=7 give n=143, φ=120, d=103. H=72 and I=73. Encrypt each byte and recombine residues modulo 11 and 13.
RSA-OAEP provides randomized public-key encryption; RSA-PSS is a probabilistic signature scheme. Use separate encryption and signing keys. SHA-256 OAEP with 2048-bit RSA supports at most 190 plaintext bytes. Signatures verify integrity and origin relative to a trusted public key, not confidentiality. Encrypt sensor=25 twice using the same OAEP key. Both ciphertexts have 256 bytes and should differ. A 2048-bit PSS signature has 256 bytes; the modified message must fail verification.
For public prime q and generator g, Alice sends A=gˣᵃ mod q and Bob B=gˣᵇ mod q. Both compute g^(xa·xb) mod q independently. Private exponents stay local; DH alone does not authenticate peers or directly encrypt messages. q=23,g=5,xa=6,xb=15 gives A=8, B=19, B⁶ mod 23=2 and A¹⁵ mod 23=2.
This isolated Boolean state-machine models a trust decision, not a network interception or implemented signature protocol. A public key must be bound to an expected identity. If required binding fails, abort. An accepted unauthenticated session does not prove identity. Required binding and unchanged value: accept and mark verified. Required binding and changed value: abort. Without binding, acceptance says nothing about identity.
Recipient publishes Y=gˣ mod q. Sender selects ephemeral k and computes C₁=gᵏ and mask K=Yᵏ mod q; C₂=mK mod q. Recipient computes K=C₁ˣ then m=C₂K⁻¹ mod q. Textbook ElGamal does not authenticate. q=19,g=10,xa=5,m=17,k=6: Y=3, K=7, C₁=11, C₂=5; inverse of 7 mod 19 is 11; recovered=17.
For prime p>3 use y²≡x³+ax+b mod p, with 4a³+27b² nonzero modulo p. Enumerate all matching y for each x. The group includes point at infinity O, which has no finite coordinate. Plot discrete points. p=17,a=b=2: (5,1) satisfies 1≡137 mod 17. There are 18 finite points plus infinity, order 19.
For distinct points with unequal x, λ=(y₂−y₁)(x₂−x₁)⁻¹ mod p, x₃=λ²−x₁−x₂ mod p, y₃=λ(x₁−x₃)−y₁ mod p. P plus its inverse gives infinity; equal noninverse points use doubling. GF(17), a=b=2, P=(5,1), Q=(6,3): numerator=2, denominator=1, inverse=1, λ=2; x₃=10,y₃=6.
For doubling λ=(3x₁²+a)(2y₁)⁻¹ mod p. Use the coordinate formulas with P=Q. If y=0, doubling gives infinity. Add P to 2P to obtain 3P. GF(17), P=(5,1): numerator=77 mod 17=9, denominator=2, inverse=9, λ=13, 2P=(6,3), 3P=(10,6). GF(23), a=b=1,P=(3,10): 2P=(7,12),3P=(19,5).
Double-and-add reads scalar bits from least significant. Start at infinity, conditionally add the current point, then double the addend. Point order is the smallest positive t with tP=O, not necessarily group order. P=(5,1) over GF(17), a=b=2. 3=11₂: add P and 2P to obtain (10,6). P has order 19.
Domain parameters include p,a,b,G, order n and cofactor h. Private scalars are 1…n−1. Exchange public points A=xaG and B=xbG; compute xaB=xbA. This local base-point model validates points and rejects infinity. Real ECDH uses standardized curves, peer authentication and KDF. GF(17),a=b=2,G=(5,1),xa=5,xb=7. G has order 19; shared point is 35G=16G.
CR57 · ECDH, HKDF and authenticated sensor protection
Ephemeral P-256 ECDH produces shared bytes; HKDF-SHA256 derives 32-byte keys using classroom context. AES-GCM uses a fresh 96-bit nonce, AAD device-1 and 128-bit tag. This provides authenticated payload protection, not authenticated peer identity or replay prevention. temperature=25.0 is 16 UTF-8 bytes; ciphertext plus tag is 32 bytes (nonce separate). Changed tag must fail verification.
CR58 · RSA versus ECC measured signature operations
RSA-3072 and P-256 have roughly comparable 128-bit classical security strength. Measure implementations, not security. Same message and SHA-256; warm up, repeat measurements, report medians and signing standard deviation. Web Crypto ECDSA uses raw r||s; Python uses variable DER encoding. RSA-3072 signature is 384 bytes; P-256 browser raw signature is 64 bytes. Python DER signature length varies. Timings depend on runtime and device.
CR59 · Hashing versus encoding and digest families
Encoding changes representation and is reversible without a secret. Hashing maps arbitrary bytes to a fixed-size digest; it is not encryption or sender authentication. MD5 and SHA-1 are historical, collision-broken algorithms, not suitable for new security designs. SHA-256, SHA-512 and SHA3-256 have different digest sizes and constructions. UTF-8 byte length may differ from character count. For abc, hexadecimal is 616263 and Base64 is YWJj. SHA-256 is ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad.
The toy digest starts at zero. For each input byte b, rotate the 8-bit state left r places then XOR with b: h_i = ROTL8(h_(i−1),r) XOR b. With r=0, order is irrelevant and equal bytes cancel. This is a deliberately weak construction, not a cryptographic hash. ABBA with rotation zero yields 00 because A XOR A = B XOR B = 0. Rotation 1 changes the intermediate states.
CR61 · Truncated hash collision and birthday bound
A collision is two distinct messages with the same digest. Preimage resistance and second-preimage resistance are different properties. For an ideal b-bit digest the approximate 50% collision threshold is sqrt(2 ln 2) × 2^(b/2). This exercise truncates SHA-256 intentionally to 4–16 bits and searches only synthetic classroom strings. It is not a collision attack on full SHA-256. An 8-bit prefix has 256 possibilities; the approximate 50% threshold is 19 samples. The first collision count depends on the selected sequence.
A controlled comparison changes one input bit while keeping message length and the hash algorithm fixed. Hamming distance counts differing digest bits; divide by digest width and multiply by 100. The bit index starts at the least significant bit of UTF-8 byte zero. Strong avalanche alone does not prove collision resistance. For a 256-bit digest, a Hamming distance of 128 corresponds to 50%. SHA-512 uses a 512-bit denominator.
CR63 · SHA-512 padding, schedule and compression rounds
SHA-512 pads a message with one bit, zeros and a 128-bit big-endian bit-length field to a multiple of 1024 bits. Sixteen input words expand to 80 words using small sigma rotations and shifts. Each round computes T1=h+Σ1(e)+Ch(e,f,g)+K[t]+W[t] and T2=Σ0(a)+Maj(a,b,c), modulo 2^64. After 80 rounds add working variables to the previous hash state. abc is 24 bits; one 1024-bit padded block. W[0]=6162638000000000, W[15]=0000000000000018. Its digest begins ddaf35a193617aba.
SHA3-256 uses a 1600-bit state of 25 lanes, each 64 bits. Its rate is 1088 bits (136 bytes) and capacity 512 bits. Domain padding uses suffix 06 and final 80 bit, with both combined when sharing the last byte. Absorption XORs input into the rate, then applies 24 rounds of theta, rho, pi, chi and iota. Squeezing reads output bytes from rate lanes in little-endian order. abc produces 3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532. A 135-byte input uses one padded block, 136 bytes use two.
A trusted reference digest can detect a modified local byte sequence. The verifier recomputes SHA-256 over received bytes and compares against that reference. A hash delivered by the same untrusted source is not independent authentication; signed firmware or a trusted authenticated manifest is required. Flipping bit zero of F (0x46) produces G (0x47), changing the firmware digest without changing length.
PBKDF2-HMAC-SHA256 derives a key from a password, salt and iteration count. Different salts make identical passwords yield different derived values. A salt need not be secret; it should be unique and randomly generated in practice. Higher iteration counts increase work; these intentionally low classroom values are not production recommendations. Use synthetic credentials only. The same synthetic password with salts lab-salt-0000001 and lab-salt-0000002 yields different 256-bit derived keys. Verification repeats derivation with the original parameters.
SHA-256 uses a 64-byte block. Normalize K to K′ by hashing keys longer than 64 bytes, then zero-padding. Compute inner=H((K′ XOR ipad)||m), tag=H((K′ XOR opad)||inner), where ipad=36 repeated and opad=5c repeated. HMAC authenticates under a shared key; it neither encrypts nor inherently prevents replay. With 20 bytes of 0b and Hi There, RFC 4231 HMAC-SHA256 is b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7.
HMAC binds the reading and sequence number to a shared key. A receiver compares tags and independently checks whether the sequence is greater than its last accepted sequence. Only acceptance advances the stored sequence. Replay prevention depends on trusted persistent freshness state and key/device identity, not HMAC alone. With initial last=0, sequence 1 and an unchanged reading, the first message is accepted; its identical replay has a valid tag but fails freshness.
CMAC derives L=AES_K(0^128), K1=dbl(L), K2=dbl(K1) using a left shift and conditional XOR of 0x87 into the low byte. CBC-style chaining starts from zero. A complete nonempty final block is XORed with K1; otherwise pad with 0x80 and zeros and XOR K2. AES encrypts each XORed chain input. Legacy raw CBC-MAC is not a safe variable-length generalization. With an all-zero classroom key L=66e94bd4ef8a2c3b884cfa59ca342b2e; K1=cdd297a9df1458771099f4b39468565c.
CR70 · Digital signatures: ECDSA file verification
A digital signature binds a digest to a private signing key; a trusted public key verifies it. This lab uses P-256 ECDSA with SHA-256 from a vetted library. Signatures contain r and s; Python uses ASN.1 DER while Web Crypto returns raw r||s. Validity depends on trusted keys, not simply the presence of a signature. An original synthetic firmware message verifies with its own public key. A modified message and a different public key must be rejected. Signature bytes can vary between runs.
Use a prime p, primitive root g and private x; y=g^x mod p. Choose k coprime to p−1. r=g^k mod p and s=k⁻¹(h−xr) mod (p−1). Verify g^h ≡ y^r r^s (mod p). The small example is for arithmetic only; never use these parameters or chosen signing nonces in real systems. For p=19, g=10, x=5, k=5, h=7, compute k inverse modulo 18 and both sides of the verification equation.
For this small fixed DSA fixture p=23, q=11, g=4, x=3, k=6, h=9, sign using r=(g^k mod p) mod q and s=k⁻¹(h+xr) mod q. Verify with w=s⁻¹ mod q, u1=hw mod q, u2=rw mod q, v=((g^u1 y^u2 mod p) mod q). A tiny digest domain can admit accidental verification collisions. DSA is historical and not recommended for new signature generation. The fixture is generated from h=9; verification succeeds for that representative. Other representatives must be evaluated by the actual equation, not presumed to fail.
Long-term keys authenticate identities; session keys protect one session. A KDC is a trusted intermediary. Rotation, expiration and revocation constrain use. This explicit model checks key validity and freshness before release.
X.509 binds a public key to subject identity via issuer signature; SAN identifies DNS names, validity limits time, key usage constrains purpose. Generate local certificates and verify the issuer signature. Signature verification alone is not full path validation.
CR75 · Certificate trust chain and revocation decisions
A valid signature is insufficient: trust anchor, intermediates, validity, hostname and applicable revocation policy all matter. Revocation checking depends on client policy and infrastructure.
CR76 · IPsec AH/ESP transport and tunnel packet layout
AH provides integrity/authentication but no confidentiality. ESP can provide confidentiality and integrity; transport protects the upper-layer payload while tunnel carries an inner IP packet. This model omits algorithm-dependent padding and outer options except specified assumptions.
CR81 · SSH transport, user authentication and channels
SSH first authenticates the server host key at transport layer, then authenticates the user, then opens multiplexed channels. Host-key trust and user-key authorization are distinct.
Local forwarding carries bytes from a client-side listening socket over SSH to a server-side destination. Remote forwarding reverses the listener location. Encryption applies to the SSH segment, not automatically to destination traffic.
A firewall evaluates packet metadata against ordered rules. First matching rule wins in this model; otherwise default deny. Stateful filtering may permit return traffic for an established session.
TCP establishes transport before TLS negotiation. The TLS 1.2 example uses authenticated ephemeral ECDHE; ChangeCipherSpec and Finished precede encrypted application data. Other TLS 1.2 cipher suites differ.
TLS 1.3 negotiates supported versions and key shares in hello messages, derives handshake keys, encrypts later handshake messages, and uses AEAD. Compatibility CCS is not a key-transition signal as in TLS 1.2.
TLS 1.3 outer record header has 5 bytes; encrypted content contains plaintext, inner content type and optional padding, plus AEAD tag (16 bytes in this example). Outer content type is application_data for encrypted records.
CR80 · Verified local TLS 1.2/1.3 and hostname failure
Use Python SSL MemoryBIO to conduct a real TLS handshake in process. Trust only a generated local CA; verify hostname; compare TLS 1.2 and 1.3 with the same data. No listener or public network is used.
CR84 · Challenge-response and mutual authentication
Challenge-response uses a fresh nonce and proof of key possession. Mutual authentication requires two direction-bound proofs to prevent reflection; this synthetic HMAC model verifies separate labels.
CR85 · Replay cache, sequence and timestamp checks
Freshness requires receiver state. A nonce cache rejects duplicates; a timestamp window rejects stale messages and assumes clock synchronization. The model assumes tag verification precedes freshness checks.
Kerberos KDC contains AS and TGS. AS issues a TGT plus client/TGS session material; TGS issues a service ticket; AP exchange uses service ticket and authenticator. Mutual authentication optionally returns AP-REP. V4/DES is historical, not recommended.
CR87 · Kerberos service authenticator and realm trust
A principal identifies a user or service in a realm. Service ticket audience, expiration and authenticator replay cache must be checked. Cross-realm trust is explicit, not implied by matching usernames.
Construct RSA public/private exponents from number theory, implement square-and-multiply, and verify encryption/decryption on bounded integer examples.
A01 · Default credentials and password-guessing vulnerabilities
A unique provisioned credential authenticates a device operator; a rate limiter bounds repeated failures. Default, weak or hardcoded credentials undermine identity verification. A dictionary is a selected set, whereas exhaustive search is the entire theoretical space.
Cameras and routers exchange authorized telemetry; management access and outbound connections are restricted. The 2016 Mirai case involved insecure Linux-based IoT devices controlled together as a botnet. Synthetic incident records describe unwanted device activity and excess aggregate load.
A device boots an approved image and preserves a tested recovery path. BrickerBot (2017) was associated with destructive changes to poorly secured devices. Virtual device state is unavailable until an authorized recovery succeeds.
A05 · Compromised devices, spam, data theft and sinkhole schemes
A sensor or camera sends only approved data to authorized recipients. Fictional records include unsolicited mail, unexpected data export and traffic sent to an invalid destination. The same compromised device can affect multiple security properties.
Five independent enrolled devices vote; a threshold of three approvals is required. One physical device is represented by three logical identities in the prepared example. Fabricated identities differ from stolen valid identities.
Seven sensor readings follow validated multi-hop paths toward a base station. The supplied anomalous topology concentrates traffic at an untrusted relay; records indicate that some readings never reach the base station.
A breadth-first spanning tree assigns each node its first parent from the base station; each accepted topology epoch triggers one rebuild. Prepared event records show repeated tree reconstructions even though connectivity is unchanged. Redundant rebuilds consume message and energy budgets.
Enrolled relays forward readings along known geographic paths. A prepared topology contains an unauthorized relay on an otherwise successful path. Delivery continues but the path is exposed.
B05 · Spoofed, altered and replayed routing information
Routing advertisements are accepted only if origin, integrity and freshness checks pass. Prepared records distinguish spoofed identity, altered content and stale genuine information; each violates a different predicate.
A validated six-hop path describes actual topology. The source contrasts a six-hop normal path with a reported two-hop shortcut. The prepared trace marks a physical/logical inconsistency.
The destination receives unique packets over a verified four-hop path. A prepared route record shows a relay receiving packets that never arrive at the destination.
Ordinary wireless loss varies across observation windows. Prepared windows include partial delivery anomalies; benign loss overlaps the anomaly distribution.
Packets arrive and payload access is authorized only at endpoints. A prepared path has full delivery but includes a hypothetical unauthorized observer.
An authorized virtual indicator command is validated before duplicate suppression. The teaching trace contains an earlier invalid event and a later legitimate event with the same reference number. Arrival order alone is not a trust decision.
A routing neighbor is eligible only when both communication directions are verified. The supplied radio adjacency matrix has neighbors that can receive a HELLO but cannot return a message.
Mesh clients reach the wireless hot spot (WHS) through transit access points (TAPs) with restricted internal state. A supplied read-only exposure snapshot shows route and state metadata disclosed without route changes.
Each transit access point has one enrolled identifier and location association. The supplied inventory contains duplicate relay identities at different positions; some clients lose service.
Mesh monitoring records both internal-state access and topology consistency. Read-only exposure, route modification and duplicate TAP incidents have different observable symptoms.
Only inventoried, necessary services are reachable from an approved network. Sample service manifests contain cleartext management and unnecessary listening services.
Device, mobile app, cloud API and administrative interfaces enforce per-request authorization. Prepared API audit records contain cross-account reads and unvalidated requests.
A firmware update is accepted only after signature, version and compatibility validation. Sample manifests include unsigned, downgraded or incompatible images.
A dependency inventory links package versions to validated advisories. Prepared components include unsupported libraries and unresolved known weaknesses.
Collect only the necessary attributes for a defined purpose. A synthetic dataset contains combinations of attributes that uniquely distinguish fictional records.
A fleet inventory maintains unique ownership, update state and retirement status. Sample registration records contain orphaned, duplicate and retired identities.
A deployment checklist verifies that insecure default features are disabled. Prepared configuration records include default credentials, public sharing and unnecessary discovery.
Production devices restrict physical access and debug interfaces. A fictional board inventory records accessible debug headers and missing enclosure controls.
D11 · Unauthenticated access and weak authentication
A service checks device identity, message integrity and freshness before acceptance. Prepared service logs include a missing identity, invalid authentication and stale messages.
D12 · Hidden backdoors and insecure password storage
A read-only firmware manifest documents accounts and credential-storage policy. Sample manifests show undocumented accounts and insecure credential storage; no real passwords are provided.
Keys have defined ownership, purpose, storage and rotation procedures. Synthetic key metadata records shared, expired and exposed keys, without key values.
A parser validates an input length before copying into a bounded buffer. Prepared length records include valid, oversized and empty inputs. A virtual memory region shows accepted or rejected lengths; no unsafe write is executed.
IoTGoat is a deliberately insecure OpenWrt-based educational firmware target. Use supplied fictional findings for the OWASP IoT categories, not a live device. Review evidence and distinguish device, link and application surfaces.
TCP establishment uses SYN, SYN/ACK and ACK; incomplete handshakes occupy pending state under the model. Prepared queue snapshots contain pending connections that have not completed establishment.
Ordinary ICMP diagnostic traffic is directed to an intended peer. A historical reflected ICMP incident is represented by fixed measured request and response totals.
UDP traffic is accepted only for explicitly required services. Historical UDP reflection differs from ICMP Smurf; fixed observed byte totals represent unnecessary reflected service traffic.
An address pool grants leases to enrolled devices and expires stale reservations. The supplied pool snapshot contains many occupied leases and few free addresses.
A service returns legitimate responses to authorized requests. A prepared incident report shows response bytes exceeding request bytes; reflection and amplification are distinct concepts.
An HTTP server accepts headers and a bounded request body, with completion and timeout policies. Fixed request-state snapshots include incomplete bodies consuming application slots.
Approved signed updates and backups support a tested device recovery path. A virtual firmware integrity failure makes the service unavailable until recovery is validated.
Authentication responses avoid disclosing account existence and recovery is available to legitimate users. Synthetic logs contain inconsistent errors and inappropriate persistent lockouts.
Compare service availability under the same observation duration. The synthetic table contrasts pending connections, reflection, lease exhaustion, slow requests, permanent unavailability and authentication abuse.
Bluetooth data access requires authorized pairing and service permission. Prepared access records contain unauthorized attempts to read fictional contact data.
Devices expose only necessary discovery metadata and protect data exchanges. Prepared observation records show discoverable identifiers and unnecessary visible metadata.
An asset inventory records device characteristics only for authorized administrators. Prepared metadata records reveal model and version information beyond a defined need.
F06 · BlueBorne historical Bluetooth vulnerabilities
An inventory records Bluetooth stack, software version and patch status. BlueBorne (2017) comprised distinct vulnerabilities in affected Android, Windows, Linux and Apple implementations, not every version of every OS. CERT-EU advisory 2017-018 distinguishes affected versions and fixes.
A wireless association changes state only following valid management events. Prepared frame records contain invalid disconnect indications and valid reconnect events.
A client verifies the expected network identity and relevant certificate configuration, not just SSID. Fictional profiles include a trusted AP and an untrusted lookalike sharing a network name.
Device identity is bound to enrollment credentials rather than a MAC address alone. Prepared registration data contains the same MAC-like fictional identifier on multiple device records.
Authenticated encrypted payloads are readable only by authorized endpoints. Offline packet descriptions contain a mixture of protected payloads and exposed metadata.
Wi-Fi enrollment requires approved credentials and a controlled configuration workflow. Fictional configurations contain legacy enrollment modes that are not required by the deployment.
G06 · Wireless jamming and interference resilience
Signal-to-noise ratio compares received signal and noise powers in the same bandwidth. Prepared receive-only samples contain degraded signal quality and missing frames.
Bluetooth, Wi-Fi and Zigbee have different association, service and frame-security assumptions. Compare prepared observations for unsolicited communication, rogue access, stale frames and interference.
IT-H01 · Primary · IoT Threat · Authentication, replay and side channels
H01 · Man-in-the-middle
A phone and virtual lock verify each other's identities and protect messages end to end. Prepared transcript records show an untrusted intermediary, mismatched peer identity and invalid integrity evidence.
IT-H02 · Primary · IoT Threat · Authentication, replay and side channels
H02 · Replay attack
Valid authenticated messages carry receiver-checked freshness information. Prepared messages include a fresh event, a duplicate, a stale event and an invalid tag.
IT-H03 · Primary · IoT Threat · Authentication, replay and side channels
H03 · Forged malicious devices
Only approved devices with enrolled credentials join the virtual asset inventory. Prepared inventory includes unrecognized replacement devices and duplicate identity claims.
IT-H04 · Primary · IoT Threat · Authentication, replay and side channels
H04 · Side-channel leakage
An implementation aims to minimize observable data-dependent differences. Two sets of harmless synthetic power-trace summaries illustrate measurable group differences, without secret-key recovery.
IT-H05 · Primary · IoT Threat · Authentication, replay and side channels
H05 · Exploit kits and vulnerability exposure
An inventory links validated advisories to assets and remediation owners. Fictional vulnerability reports indicate known weaknesses and unsupported components that can be abused by automated exploit ecosystems.
Virtual building control separates monitoring and authorized commands, with safe fallback. Fictional records cover access-control errors, MITM, DoS, eavesdropping, control hijacking, firmware reverse-engineering risk and chained weaknesses; the 2016 Finnish heating disruption illustrates consequences.
Industrial assets use role-based access, network zones and controlled maintenance. Prepared records cover physical/remote access, reconnaissance exposure, chained failures, spear phishing, eavesdropping and bluebugging risks.
Smart-home apps, voice skills and payment forms have verified identities and scoped access. Fictional cases include skill squatting (confusing voice-app names), formjacking (payment form data theft), MITM, unapproved camera access and service loss.
Synthetic medical observations are authenticated and redundant delivery is monitored. Prepared incidents include jamming, sinkhole, Sybil, bluesnarfing, MITM and Zigbee end-device battery exhaustion risks.
A fictional transport model compares authenticated telemetry with independent reference observations. Prepared records flag impersonation, GPS inconsistency, wormhole/blackhole observations, wireless freshness and rolling-code risks.
A virtual water-monitoring network authenticates messages and maintains independent monitoring. Prepared records contain interference, historical fragmentation-related weakness and missing telemetry.
Irrigation recommendations depend on validated sensor observations, not arbitrary network inputs. Prepared observations include misconfiguration, path-based DoS, unauthorized reprogramming, GPS inconsistency and stale sensor readings.
I10 · Cross-sector threat and consequence analysis
Use comparable observation windows but distinguish consequence severity from technical availability. A prepared set compares consumer, building, industrial, medical, agriculture, transport, water and marine service disruption.
Notice, consent, purpose limitation and minimization constrain collection and sharing. Combining entirely fictional attribute groups can create unique records. The six issues include notice/consent, unexpected sharing, aggregation/profiling, harm, PII and re-identification.
IT-K02 · Primary · IoT Threat · Malware and ransomware
K02 · Virus classifications
A verified system records boot, application and file-integrity states. Macro, boot-sector, multipartite, polymorphic, metamorphic and stealth categories describe different host, transformation or concealment characteristics.
IT-K04 · Primary · IoT Threat · Malware and ransomware
K04 · Ransomware lifecycle
Backups and approved software support restoration of normal service. A fictional incident follows discovery, containment and recovery after service unavailability; ransomware may also involve data theft.
IT-K05 · Primary · IoT Threat · Malware and ransomware
K05 · Smart thermostat ransomware
A virtual thermostat maintains an approved configuration and local fallback. The 2016 thermostat demonstration illustrates physical consequences of a locked device. The fixture only represents service availability.
IT-K06 · Primary · IoT Threat · Malware and ransomware
K06 · Comparative malware defence
Defensive measures include patching, segmentation, integrity monitoring, application controls and tested backups. Compare prepared service availability observations for several inert incident categories.
An authorized asset inventory contains device class, service, version, ownership and exposure fields. Shodan, Censys and Thingful are discussed as historical discovery resources. Inspect the six supplied fictional records for unapproved service, unknown owner or missing version.
A virtual receiver validates authenticity and freshness of message-history records. Fixed and rolling codes differ in reuse; RFCrack and rfcat-rolljam appear as historical RF assessment tools. Prepared records include duplicate and stale messages.
A coordinator, routers and end devices exchange frames within a managed network. Prepared frame metadata include valid, invalid and stale counter observations. Attify and KillerBee are historical assessment tools.
Software-defined radio represents signal processing in software; frequency, bandwidth and received power describe observations. Fixed fictional spectrum readings compare ordinary and degraded channel conditions. HackRF One is a half-duplex SDR.
A read-only firmware manifest lists header, kernel, filesystem, applications and integrity metadata. Firmware Mod Kit, Firmwalker and Firmalyzer are discussed in their assessment roles; supplied records identify missing or inconsistent integrity evidence.
An authorized capture records protocol, direction, length and validation status. Wireshark, tcpdump, CloudShark, Ubiqua, Perytons, Suphacap and Open Sniffer are discussed as analysis tools. Inspect prepared metadata for anomalies.
A bounded parser validates input lengths before accepting data. beSTORM, IoTSeeker, IoT Inspector, Bitdefender Home Scanner and Metasploit Pro are historical assessment tools; this exercise uses only supplied length records.
An approved board documentation set records debug interfaces and production access restrictions. JTAG and JTAGulator are discussed as hardware debugging and assessment concepts; sample records flag exposed production interfaces.
Defensive assessment uses authorized asset discovery, validation, evidence, containment and restoration. The five historical hacking phases are information gathering, scanning, launching attacks, remote access and maintaining access. Map each to defensive review; Metasploit, IoTsploit and GATTack.io are discussed without operational use.
IT-M01 · Primary · IoT Threat · SCADA and industrial control
M01 · SCADA authentication and authorization
SCADA supervisory interfaces and controllers enforce identity and role checks for machine-to-machine commands. Prepared records show shared/default credentials, cleartext sessions and insufficient authorization in a virtual ICS.
IT-M02 · Primary · IoT Threat · SCADA and industrial control
M02 · Unpatched SCADA and legacy systems
A signed patch is checked for vendor compatibility, tested and staged within an approved maintenance window. Prepared patch records represent an unsupported dependency and scheduled service downtime.
IT-N01 · Primary · IoT Threat · E-passport and RFID threats
N01 · E-passport security
A contactless document uses reader access controls and protects sensitive chip data. Prepared fictional reader observations illustrate skimming and identity-theft risk; no real passport fields are used.
IT-N02 · Primary · IoT Threat · E-passport and RFID threats
N02 · RFID spoofing
Reader observations are reconciled with trusted tag enrollment. Prepared inventory includes an unrecognized identity claim; spoofing differs from copying a valid identifier.
IT-N03 · Primary · IoT Threat · E-passport and RFID threats
N03 · RFID cloning
Each enrolled tag should have consistent inventory observations. Prepared logs contain duplicates of fictional tag identities at inconsistent positions.
IT-N06 · Primary · IoT Threat · E-passport and RFID threats
N06 · RFID shielding
A reader receives tag responses only when link conditions permit. Prepared received-power observations represent attenuation; shielding may be used defensively or cause missing reads.
Distinguish a digest from confidentiality and origin authentication. Observe SHA-256 and SHA-512 concepts, digest comparison and avalanche effects using actual SHA-256 computations.
Investigate how a signed or anchored emissions-monitoring record can be checked by an independent auditor, and why sensor truth remains outside the ledger.
Compare a consistency-first replicated store against an availability-first store during a network partition. Explore disintermediation, replication and the CAP trade-off.
Blockchain elements: Merkle trees and light clients
Build the eight-transaction binary hash tree shown in the module. Inspect ordered hash inputs, root and logarithmic inclusion proof with a trusted header root.
Compare observer decisions with conflicting validator messages and inspect a 3-of-4 quorum. Explore a simplified count versus stake-weighted voting rule.
Hyperledger: permissioned transactions and world state
Follow identity, endorsement, ordering and validation using the whitepaper enterprise requirements and an explicitly modern Fabric-style execute-order-validate teaching abstraction.