Skip to main content
IoT
PSUT Engineering StudioPrincess Sumaya University for Technology
Student Edition
Cyber Defense StudioIoT Security and PrivacyExperimentsWorkspaces
Home / IoT Security and Privacy / Cryptography Engineering
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
CRYPTOGRAPHY ENGINEERING · CR20 · AES
IoT Security and Privacy

AES · round-by-round avalanche

Use plaintext 0123456789ABCDEFFEDCBA9876543210, key 0F1571C947D9E8590CB7ADD6AF7F6798, and a one-bit change at bit 120 (first byte’s low bit).

CR20 · Laboratory mentorAsk about the current operation and its intermediate values.
CR20 · Academic orientation

Scope and objectives

Scope of the experiment

Compare states at matching algorithm boundaries; changing both key and plaintext confounds the effect. Key expansion makes key changes affect subsequent subkeys.

The focus of this experiment is to define full-state Hamming distance and percentage diffusion. Students then compare plaintext and key bit changes at corresponding AES rounds, and interpret nonmonotonic measurements without asserting security from one trial. The Concepts view explains the operation before the practical work; the Simulation view is used to examine reference and changed inputs, not to substitute for actual measurements.

Learning objectives

  • Define full-state Hamming distance and percentage diffusion.
  • Compare plaintext and key bit changes at corresponding AES rounds.
  • Interpret nonmonotonic measurements without asserting security from one trial.
  • Record the relevant inputs, intermediate states and final verification result before changing the reference configuration.
  • Compare the reference calculation or decision with an independent implementation or authorized observation; state any discrepancy and the applicable model boundary.

Expected learning outcomes

On completion, students can define full-state Hamming distance and percentage diffusion, compare plaintext and key bit changes at corresponding AES rounds, and interpret nonmonotonic measurements without asserting security from one trial.

Required deliverables

Submit the derivation or state trace for the named operation, the exact reference and changed configurations, the associated simulator or practical evidence, and a short validation statement addressing interpret nonmonotonic measurements without asserting security from one trial. Separate predicted values from observations.

Prerequisite knowledge and related learning

Use the curriculum sequence and the Concepts section for prerequisite terminology. After completion, continue to AES-ECB · block processing and errors.

Environment and experimental methodology

A standard browser and the experiment-specific Python implementation or Colab notebook. Where the practical uses a protocol model, model results are distinguished from actual local cryptographic operations.

Begin with a manual prediction, record the baseline, change one independent condition at a time, and compare the resulting trace or measurements with the original prediction. Record observations and uncertainty separately from reference values. Follow the experiment’s specific procedure, safety limits, and acceptance checks.

01 · Experiment overview

CR20 · AES · round-by-round avalanche

Use plaintext 0123456789ABCDEFFEDCBA9876543210, key 0F1571C947D9E8590CB7ADD6AF7F6798, and a one-bit change at bit 120 (first byte’s low bit). The baseline ciphertext is FF0B844A0853BF7C6934AB4364148FB9. For each AddRoundKey state count differing bits out of 128. Separate plaintext-bit and key-bit trials; keep other inputs fixed. Compare AES with DES using percentages, not raw bit counts. A single trial does not prove security.

Before starting

Environment: standard computer, browser and Python/WSL.

Simulation: Editable JavaScript calculation

Technical scope: Classroom computation on a standard computer. Educational cipher code is not a production security implementation.

Complete the six stages in order. Use the same experiment inputs when comparing manual, browser and Python results.

02 · Concepts and mathematical foundations

Use plaintext 0123456789ABCDEFFEDCBA9876543210, key 0F1571C947D9E8590CB7ADD6AF7F6798, and a one-bit change at bit 120 (first byte’s low bit). The baseline ciphertext is FF0B844A0853BF7C6934AB4364148FB9. For each AddRoundKey state count differing bits out of 128. Separate plaintext-bit and key-bit trials; keep other inputs fixed. Compare AES with DES using percentages, not raw bit counts. A single trial does not prove security.

Learning objectives

Calculate the named operation, inspect its intermediate values, reproduce the result in Python, and explain one controlled change. Prerequisites: binary/hexadecimal arithmetic; complete preceding labs in the same topic where applicable.

Before starting

Environment: standard computer, browser and Python/WSL.

Simulation: Editable JavaScript calculation

Technical scope: Classroom computation on a standard computer. Educational cipher code is not a production security implementation.

Controlled avalanche experiments

1 · Principles and purpose

Compare states at matching algorithm boundaries; changing both key and plaintext confounds the effect. Key expansion makes key changes affect subsequent subkeys.

2 · Mathematical and algorithmic foundations

Hamming distance \(d_{r}\)=popcount(\(S_{r}\)⊕S′ᵣ), fraction \(d_{r}\)/128. Report distribution across several bit positions; a finite sample cannot establish the strict avalanche criterion.

3 · Worked teaching example

For 128-bit states differing in only the least significant bit, d=1 and percentage=0.78125%. Later diffusion may increase or decrease observed distance by chance. Compare plaintext and key experiments separately.

Verified default trace · 11 intermediate states

Given parameters (teaching example):

{
  "plaintext": "0123456789ABCDEFFEDCBA9876543210",
  "key": "0F1571C947D9E8590CB7ADD6AF7F6798",
  "bit": "120"
}
StageComputed values
1{ "step": "0 AddRoundKey", "base": "0E3634AECE7225B6F26B174ED92B5588", "plaintext_flip": "0F3634AECE7225B6F26B174ED92B5588", "key_flip": "0F3634AECE7225B6F26B174ED92B5588", "plaintext_bits": 1, "key_bits": 1, "plaintext_pct": 0.78125, "key_pct": 0.78125 }
2{ "step": "1 AddRoundKey", "base": "657470750FC7FF3FC0E8E8CA4DD02A9C", "plaintext_flip": "C4A9AD090FC7FF3FC0E8E8CA4DD02A9C", "key_flip": "C5A9AD090EC7FF3FC1E8E8CA4CD02A9C", "plaintext_bits": 20, "key_bits": 22, "plaintext_pct": 15.625, "key_pct": 17.1875 }
3{ "step": "2 AddRoundKey", "base": "5C7BB49A6B72349B05A2317FF46D1294", "plaintext_flip": "FE2AE569F7EE8BB8C1F5A2BB37EF53D5", "key_flip": "90905FA9563356D15F3760F3B8259985", "plaintext_bits": 58, "key_bits": 58, "plaintext_pct": 45.3125, "key_pct": 45.3125 }
4{ "step": "3 AddRoundKey", "base": "7115262448DC747E5CDAC7227DA9BD9C", "plaintext_flip": "EC093DFB7C45343D689017507D485E62", "key_flip": "18AEB7AA794B3B66629448D575C7CEBF", "plaintext_bits": 59, "key_bits": 67, "plaintext_pct": 46.09375, "key_pct": 52.34375 }
5{ "step": "4 AddRoundKey", "base": "F867AEE8B437A5210C24C1974CFFEABC", "plaintext_flip": "43EFDB697244DF808E8D9364EE0AE6F5", "key_flip": "F81015F993C978A876AE017CB49E7EEC", "plaintext_bits": 61, "key_bits": 63, "plaintext_pct": 47.65625, "key_pct": 49.21875 }
6{ "step": "5 AddRoundKey", "base": "721EB200BA06206DCBD4BCE704FA654E", "plaintext_flip": "7B28A5D5ED643287E006C099BB375302", "key_flip": "5955C91B4E769F3CB4A94768E98D5267", "plaintext_bits": 68, "key_bits": 81, "plaintext_pct": 53.125, "key_pct": 63.28125 }
7{ "step": "6 AddRoundKey", "base": "0AD9D85689F9F77BC1C5F71185E5FB14", "plaintext_flip": "3BC2D8B6798D8AC4FE36A1D891AC181A", "key_flip": "DC60A24D137662181E45B8D3726B2920", "plaintext_bits": 64, "key_bits": 70, "plaintext_pct": 50.0, "key_pct": 54.6875 }
8{ "step": "7 AddRoundKey", "base": "DB18A8FFA16D30D5F88B08D777BA4EAA", "plaintext_flip": "9FB8B5452023C70280E5C4BB9E555A4B", "key_flip": "FE8343B8F88BEF66CAB7E977D005A03C", "plaintext_bits": 67, "key_bits": 74, "plaintext_pct": 52.34375, "key_pct": 57.8125 }
9{ "step": "8 AddRoundKey", "base": "F91B4FBFE934C9BF8F2F85812B084989", "plaintext_flip": "20264E1126B219AEF7FEB3F9B2D6DE40", "key_flip": "DA7DAD581D1725C5B72FA0F9D9D1366A", "plaintext_bits": 65, "key_bits": 67, "plaintext_pct": 50.78125, "key_pct": 52.34375 }
10{ "step": "9 AddRoundKey", "base": "CCA104A13E678500FF59025F3BAFAA34", "plaintext_flip": "B56A0341B2290BA7DFDFBDDCD8578205", "key_flip": "0CCB4C66BBFD912F4B511D72996345E0", "plaintext_bits": 61, "key_bits": 59, "plaintext_pct": 47.65625, "key_pct": 46.09375 }
11{ "step": "10 AddRoundKey", "base": "FF0B844A0853BF7C6934AB4364148FB9", "plaintext_flip": "612B89398D0600CDE116227CE72433F0", "key_flip": "FC8923EE501A7D207AB670686839996B", "plaintext_bits": 58, "key_bits": 53, "plaintext_pct": 45.3125, "key_pct": 41.40625 }

Recorded result

{
  "plaintext_bits": 58,
  "key_bits": 53
}

Captured earlier local execution. Randomized values and timing can differ; compare the invariant.

4 · Verification and experimental interpretation

Step through the following visualization and compare the named operation with the corresponding computed state. Check the mathematical invariant, inverse operation or protocol acceptance condition. Change one input at a time; distinguish a measured output from a prediction.

Mathematical representation and interpretation

Normalized Hamming distance

A and B are corresponding w-bit states; wt counts the one bits. Compare equal-width states at the same transformation boundary.

\[d(A,B)=\operatorname{wt}(A\oplus B),\qquad \eta=100\frac{d(A,B)}{w}\%\]

For w=8 and states 0xA5 and 0xA1, XOR gives 0x04: one changed bit, or 12.5%.

Concept animation · AES avalanche measurements

Explore the teaching example independently of the simulator. Each step reveals an operation, data relationship or calculated state. The Simulation view has separate editable inputs.

Hamming distance across algorithm states0326496128Plaintext change: 1 bitsKey change: 1 bits012345678910State index (one modified input bit; no monotonicity guarantee)Hamming distance across algorithm states0326496128Plaintext change: 20 bitsKey change: 22 bits012345678910State index (one modified input bit; no monotonicity guarantee)Hamming distance across algorithm states0326496128Plaintext change: 58 bitsKey change: 58 bits012345678910State index (one modified input bit; no monotonicity guarantee)Hamming distance across algorithm states0326496128Plaintext change: 59 bitsKey change: 67 bits012345678910State index (one modified input bit; no monotonicity guarantee)Hamming distance across algorithm states0326496128Plaintext change: 61 bitsKey change: 63 bits012345678910State index (one modified input bit; no monotonicity guarantee)Hamming distance across algorithm states0326496128Plaintext change: 68 bitsKey change: 81 bits012345678910State index (one modified input bit; no monotonicity guarantee)Hamming distance across algorithm states0326496128Plaintext change: 64 bitsKey change: 70 bits012345678910State index (one modified input bit; no monotonicity guarantee)Hamming distance across algorithm states0326496128Plaintext change: 67 bitsKey change: 74 bits012345678910State index (one modified input bit; no monotonicity guarantee)Hamming distance across algorithm states0326496128Plaintext change: 65 bitsKey change: 67 bits012345678910State index (one modified input bit; no monotonicity guarantee)Hamming distance across algorithm states0326496128Plaintext change: 61 bitsKey change: 59 bits012345678910State index (one modified input bit; no monotonicity guarantee)Hamming distance across algorithm states0326496128Plaintext change: 58 bitsKey change: 53 bits012345678910State index (one modified input bit; no monotonicity guarantee)

Step 1 of 11 · 0 AddRoundKey

Teaching example only; inspect live calculations or real practical evidence separately.

0 AddRoundKey

base
0E3634AECE7225B6F26B174ED92B5588
plaintext_flip
0F3634AECE7225B6F26B174ED92B5588
key_flip
0F3634AECE7225B6F26B174ED92B5588
plaintext_bits
1
key_bits
1
plaintext_pct
0.78125
key_pct
0.78125
Shared research workbenches · network designer & advanced studies
Concurrent-device simulation & Monte Carlo research
Distributed digital twin · topology, protocol & battery research

03 · Interactive simulation

Baseline diagram loaded. Interactive engine initializing…

Verified baseline reference — use the live workstation below to explore steps and compare inputs.
CR20 2 AddRoundKeyAES avalanche · compare identical round boundariesBaseline5C6B05F47B72A26DB43431129A9B7F94Plaintext changedFEF7C1372AEEF5EFE58BA25369B8BBD5Key changed90565FB8903337255F566099A9D1F385Byte 0 · plaintext difference 3 bits; key difference 4 bits0%25%50%75%100%Plaintext: 58/128Key: 58/128Highlighted bytes differ; plot counts individual bits, not bytes.

Edit the fields and choose Recompute. Use step controls to inspect real calculated states. Hexadecimal byte fields are written without 0x; numeric fields accept decimal or 0x notation.

Select an algorithm step to view its calculated diagram. The byte inspector uses index 4c+r; in row/column or XOR labs it jumps to the corresponding operation. Matrix values follow the representation selector; arithmetic annotations use hexadecimal. On narrow screens, scroll the diagram horizontally to inspect every label.

Calculated result

{
  "plaintext_bits": 58,
  "key_bits": 53
}
All intermediate trace rows

Guided simulation activity

Use the baseline inputs shown above. Predict a result, advance one operation at a time, inspect the intermediate state, then change only the parameter specified in the Experiments view. Export the trace and compare it with your manual derivation.

Continue to practical experiments →

04 · Experiments and engineering investigations

Analytical preparation — before Python

Use plaintext 0123456789ABCDEFFEDCBA9876543210, key 0F1571C947D9E8590CB7ADD6AF7F6798, and a one-bit change at bit 120 (first byte’s low bit). The baseline ciphertext is FF0B844A0853BF7C6934AB4364148FB9. For each AddRoundKey state count differing bits out of 128. Separate plaintext-bit and key-bit trials; keep other inputs fixed. Compare AES with DES using percentages, not raw bit counts. A single trial does not prove security.

Predict the baseline result before revealing the calculated state. A controlled comparison changes the named input while keeping the other conditions fixed. Record an observed value separately from an expected value.

Part A · Independent theoretical exercises

Complete each question before running the simulator or Python. Show calculations or protocol traces. The teaching example is a method, not a substitute for the assigned values.

01 · Application and derivation

Application and derivation · Independent work

With fixed baseline key, flip the second least-significant plaintext bit and calculate the round-0 Hamming distance manually. Repeat for a key bit. Record subsequent corresponding round states and convert distances to percentages; explain why the values need not increase monotonically.

02 · Data interpretation

Data interpretation · Independent work

In a 128-bit avalanche trial, rounds show 12,63,57,68 changed bits. Convert to percentages and assess a claim that diffusion must increase every round.

Required evidence: state the expected invariant or acceptance condition; record hand-derived results, compare with the simulator or Python trace, and explain the first discrepancy. Do not report a predicted value as a measurement.

Expanded independent theoretical exercise bank

Progress from calculation and interpretation to diagnosis and controlled engineering design. Complete the questions without opening the simulation first; show intermediate steps.

Intermediate · Alternate configuration

Independent theoretical exercise · CR20-01

For the separate teaching-test configuration plaintext: 0123456789ABCDEFFEDCBA9876543210; key: 0F1571C947D9E8590CB7ADD6AF7F6798; bit: 7, predict plaintext_bits using the relevant operation or decision rule. Show intermediate work and state whether this is a deterministic result.

Intermediate · Interpret a computation state

Independent theoretical exercise · CR20-02

A teaching trace for AES · round-by-round avalanche contains step: 1 AddRoundKey; base: 657470750FC7FF3FC0E8E8CA4DD02A9C; plaintext_flip: C4A9AD090FC7FF3FC0E8E8CA4DD02A9C; key_flip: C5A9AD090EC7FF3FC1E8E8CA4CD02A9C; plaintext_bits: 20. Explain the role of key_pct (recorded value 17.1875) and identify the rule or input that determines it. Distinguish an intermediate state from the final result.

Intermediate · Compare two recorded states

Independent theoretical exercise · CR20-03

The first and final trace records show plaintext_bits = 1 and 58. Calculate the signed difference and explain whether it is an operation count, a state value or a measurement.

Challenging · Controlled algorithm verification

Independent theoretical exercise · CR20-04

Plan a comparison of plaintext: 0123456789ABCDEFFEDCBA9876543210; key: 0F1571C947D9E8590CB7ADD6AF7F6798; bit: 120 with plaintext: 0123456789ABCDEFFEDCBA9876543210; key: 0F1571C947D9E8590CB7ADD6AF7F6798; bit: 7. Record the dependent value plaintext_bits, identify the changed factor(s), and describe the verification and failure criterion without claiming a real security measurement.

Part B · Guided simulation and practical procedure

Before starting — tools and setup

Standard computer; extract the WSL toolkit into a new directory. For the browser activity, use the integrated workstation. Editable browser calculation

Install Python dependencies only if required by the selected toolkit README. Use its requirements file and virtual environment instructions.

Open complete, verified WSL commands in Part C ↓

01

Measure plaintext and key avalanche at matching round boundaries

  1. Write a prediction using the worked calculation in Concepts.
  2. Load the baseline plaintext, key and bit 120. Use round 0 and round 1 to calculate XOR differences for a selected byte. Record both distances for every AddRoundKey step. Export the trace and plot distance percentages.
  3. Export the trace and compare against the reference only after predicting.

Experimental inputs

Experimental reference · json
{"plaintext":"0123456789ABCDEFFEDCBA9876543210","key":"0F1571C947D9E8590CB7ADD6AF7F6798","bit":"120"}
Verified baseline reference (check after predicting)
Experimental reference · json
{"plaintext_bits":58,"key_bits":53}

Compare your baseline with the verified reference output below; for runtime-dependent results, compare invariants and report actual measurements instead of expecting identical timing or randomly generated values.

Evidence to record

Bit position, round number, baseline and modified state, plaintext/key Hamming distance and percentage, final mean and range across trials.

Run baseline →
02

Part D · Controlled experiment — Measure plaintext and key avalanche at matching round boundaries

  1. Keep plaintext and key fixed; repeat bit positions 0, 7, 15 and 31. For each trial compare final distances, compute mean and range across trials, and compare with normalized DES distances from CR06.
  2. Record the conditions held constant and complete the trial table.
  3. Measure Bit position, round number, baseline and modified state, plaintext/key Hamming distance and percentage, final mean and range across trials. Explain the first differing operation and verify inverse recovery where applicable.
TrialInput configurationPredictionObservedVerification
1{"plaintext":"0123456789ABCDEFFEDCBA9876543210","key":"0F1571C947D9E8590CB7ADD6AF7F6798","bit":"120"}
2{"plaintext":"0123456789ABCDEFFEDCBA9876543210","key":"0F1571C947D9E8590CB7ADD6AF7F6798","bit":"0"}
3{"plaintext":"0123456789ABCDEFFEDCBA9876543210","key":"0F1571C947D9E8590CB7ADD6AF7F6798","bit":"7"}
4{"plaintext":"0123456789ABCDEFFEDCBA9876543210","key":"0F1571C947D9E8590CB7ADD6AF7F6798","bit":"15"}
5{"plaintext":"0123456789ABCDEFFEDCBA9876543210","key":"0F1571C947D9E8590CB7ADD6AF7F6798","bit":"31"}

Use the table as a recording template; enter your own measured values in the field below or reproduce it in your report.

Return to simulation →
03

Part E/F · Independent Python verification and deliverables

  1. Download the notebook or toolkit and run the default example.
  2. Reproduce each assigned trial using the notebook or edit a copy of example-input.json and use python3 lab.py --params example-input.json. Compare the browser and Python trace at the same step.
  3. Complete the independent assessment below without copying the worked baseline. Explain discrepancies and distinguish mathematical results from security claims.
Additional investigation instructions

A controlled comparison changes one independent input while holding other inputs fixed, then measures its effect on the dependent output. A baseline is the unmodified run. Evidence-based reasoning means citing the actual observed values, not merely asserting that an algorithm is secure.

  1. Run the supplied default values and record the first and final state.
  2. Predict the effect before changing anything. Change bit 120 (worked example), then 0, 7 and 15 in separate runs. First verified alternate: {"bit": "7"}.
  3. Keep base plaintext, key and round configuration.
  4. Measure Hamming distance and percentage in every corresponding round.
  5. Restore the baseline and repeat with another valid input. Locate the first differing calculation.
  6. Submit a comparison table, a trace JSON or screenshots of relevant steps, and a short conclusion with an explicit limitation.
TrialChanged inputFixed conditionsPredictionMeasured valueReason / limitation
BaselineNoneDefaultStudent predictionRecord traceExplain
Trial 1Specified changeUnchanged inputsStudent predictionRecord traceExplain

Part C · Python, Google Colab and WSL

The standalone implementation uses the same synthetic baseline and calculations as the browser. In Colab, download the notebook, open Colab and upload it using File → Upload notebook. Run all cells in order.

WSL / Linux execution workflow

Use Ubuntu or Kali WSL, not PowerShell. Download the toolkit above to your computer. If Python, venv or unzip is missing, install these prerequisites once (requires administrator permission and network access).

Optional prerequisites · bash
sudo apt update
sudo apt install -y python3 python3-venv unzip

In WSL, enter the actual downloaded ZIP path when prompted (for example, a file under /mnt/c/Users/…/Downloads). Extract to a new, dedicated directory. If this directory already exists from a previous extraction, use the existing verified toolkit or choose a clean directory rather than overwriting it.

Step 1 · Extract · bash
read -r -p "Full path to PSUT_V22_9_9_Cryptography_WSL.zip: " ZIP
DEST="$HOME/psut-crypto-v22.9.9"
if [ -f "$ZIP" ] && [ ! -e "$DEST" ]; then
    mkdir "$DEST" && unzip "$ZIP" -d "$DEST"
else
    echo "Check ZIP path and use a fresh destination."
fi

Create the isolated environment in the extracted toolkit root, activate it, then enter this experiment’s actual folder. Install only its declared dependencies. A comment-only requirements file requires no third-party packages.

Step 2 · Activate and install · bash
cd ~/psut-crypto-v22.9.9
python3 -m venv .venv
source .venv/bin/activate
cd CR20
ls
python -m pip install -r requirements.txt

Execute the default run and save the genuine program output. Then run the supplied regression test and the baseline fixture through the explicit input interface.

Step 3 · Run and verify · bash
python lab.py | tee my-results.json
python test_lab.py
python lab.py --params example-input.json
python -m json.tool my-results.json

To change inputs, copy example-input.json, edit the copy in a text editor and run the command below. The original fixture is preserved.

Step 4 · Change an input · bash
cp example-input.json my-input.json
# Edit my-input.json with your preferred editor.
python lab.py --params my-input.json

These scripts terminate normally. Use Ctrl+C to stop a long-running calculation if needed. When finished, leave the isolated virtual environment; no global service cleanup is required for these local examples.

Step 5 · Finish · bash
deactivate

Declared dependencies: # Standard library only for core experiment

Expected terminal output — captured local execution

This excerpt contains the actual first trace step and final result from python lab.py, followed by the actual regression test output. Full stdout is in CR20/verified-output.txt inside the toolkit. Timing, random signatures, keys, certificate fields and implementation-dependent sizes can vary; compare the invariant and record your own observations.

Verified execution excerpt · text
{
  "first_step": {
    "step": "0 AddRoundKey",
    "base": "0E3634AECE7225B6F26B174ED92B5588",
    "plaintext_flip": "0F3634AECE7225B6F26B174ED92B5588",
    "key_flip": "0F3634AECE7225B6F26B174ED92B5588",
    "plaintext_bits": 1,
    "key_bits": 1,
    "plaintext_pct": 0.78125,
    "key_pct": 0.78125
  },
  "result": {
    "plaintext_bits": 58,
    "key_bits": 53
  }
}

Test script output:
PASS

Check the output JSON and the test exit status. An assertion error means the expected invariant was not met. If Python reports a missing module, activate the environment and install the experiment’s requirements file; if a file is missing, check pwd and ls.

Inspect the documented Python implementation
Documented Python implementation · python
# ============================================================
# CR20 | Educational implementation and trace functions
# Copyright © 2026/2027 Dr. Mohammad Alja’afreh
# PSUT IoT Engineering Studio | Educational, synthetic inputs
# ============================================================
from functools import lru_cache

# Multiply binary polynomials by XORing shifted copies; no integer carries.
def pmul(a,b):
    r=0
    for i in range(b.bit_length()):
        if b>>i&1: r ^= a<<i
    return r

# Cancel the leading polynomial term repeatedly, retaining quotient and remainder.
def pdiv(a,b):
    if not b: raise ValueError('Zero polynomial divisor')
    q=0; steps=[]
    while a and a.bit_length()>=b.bit_length():
        k=a.bit_length()-b.bit_length(); old=a; q ^= 1<<k; a ^= b<<k
        steps.append((old,b<<k,a))
    return q,a,steps

# Reduce the carry-free product by the selected irreducible polynomial.
def gm(a,b,m=0x11b): return pdiv(pmul(a,b),m)[1]

# Use polynomial extended Euclid to find a multiplicative inverse.
def gi(a,m=0x11b):
    if not a: raise ValueError('Zero has no multiplicative inverse')
    r,s=m,a; t,u=0,1
    while s:
        q,v,_=pdiv(r,s); r,s=s,v; t,u=u,t^pmul(q,u)
    if r!=1: raise ValueError('Not invertible')
    return pdiv(t,m)[1]

def hx(n,w=2): return f'{n:0{w}X}'

# Wrap shifted bits around the fixed word width instead of discarding them.
def rot(x,k,w): return ((x<<k)|(x>>(w-k)))&((1<<w)-1)

def hamming(a,b): return sum((x^y).bit_count() for x,y in zip(a,b))

def xor(a,b): return bytes(x^y for x,y in zip(a,b))

def hexs(a): return bytes(a).hex().upper()

def row(label,**values): return {'step':label,**values}

# Compute the public AES substitution from a field inverse and affine transform.
@lru_cache(maxsize=256)
def sb(a):
    v=gi(a) if a else 0
    return v^rot(v,1,8)^rot(v,2,8)^rot(v,3,8)^rot(v,4,8)^0x63

def invsub(a): return next(i for i in range(256) if sb(i)==a)

# Rotate each matrix row while preserving column-major state layout.
def shift(s,inv=False): return bytes(s[4*((i//4+(-1 if inv else 1)*(i%4))%4)+i%4] for i in range(16))

# Multiply each column by the forward or inverse circulant matrix in GF(2^8).
def mix(s,inv=False):
    a=[14,11,13,9] if inv else [2,3,1,1]
    return bytes(gm(s[4*(i//4)+(i%4)%4],a[0])^gm(s[4*(i//4)+(i%4+1)%4],a[1])^gm(s[4*(i//4)+(i%4+2)%4],a[2])^gm(s[4*(i//4)+(i%4+3)%4],a[3]) for i in range(16))

# Generate all round words using Nk-dependent transformations and Rcon.
def expand(key):
    nk=len(key)//4
    if len(key) not in (16,24,32): raise ValueError('AES key must be 16, 24 or 32 bytes')
    w=[key[i:i+4] for i in range(0,len(key),4)]; trace=[]; rc=1
    for i in range(nk,4*(nk+7)):
        t=w[-1]; operation='XOR previous word'
        if i%nk==0:
            t=bytes(sb(x) for x in t[1:]+t[:1]); t=xor(t,bytes([rc,0,0,0])); operation=f'RotWord, SubWord, Rcon={hx(rc)}'; rc=gm(rc,2)
        elif nk==8 and i%nk==4: t=bytes(sb(x) for x in t); operation='SubWord'
        w.append(xor(w[i-nk],t)); trace.append(row(f'w[{i}]',operation=operation,base=hexs(w[i-nk]),temp=hexs(t),word=hexs(w[i])))
    return [b''.join(w[i:i+4]) for i in range(0,len(w),4)],trace

# Trace each reversible AES stage, omitting MixColumns in the final encryption round.
def aes(p,key,dec=False):
    if len(p)!=16: raise ValueError('Exactly 16-byte AES block')
    keys,_=expand(key); nr=len(keys)-1; s=p; trace=[row('Input',state=hexs(s))]
    def snap(r,name): trace.append(row(f'{r} {name}',state=hexs(s)))
    if not dec:
        s=xor(s,keys[0]); snap(0,'AddRoundKey')
        for r in range(1,nr+1):
            s=bytes(sb(x) for x in s); snap(r,'SubBytes'); s=shift(s); snap(r,'ShiftRows')
            if r<nr: s=mix(s); snap(r,'MixColumns')
            s=xor(s,keys[r]); snap(r,'AddRoundKey')
    else:
        s=xor(s,keys[nr]); snap(nr,'AddRoundKey')
        for r in range(nr-1,-1,-1):
            s=shift(s,True); snap(r,'InvShiftRows'); s=bytes(invsub(x) for x in s); snap(r,'InvSubBytes'); s=xor(s,keys[r]); snap(r,'AddRoundKey')
            if r: s=mix(s,True); snap(r,'InvMixColumns')
    return s,trace

def n(s): return int(s,0)

def b(s): return bytes.fromhex(s)

def exact(s,size):
    v=b(s)
    if len(v)!=size: raise ValueError(f'Expected {size} bytes')
    return v

def bitflip(s,bit):
    if not 0<=bit<8*len(s): raise ValueError('Bit out of range')
    t=bytearray(s); t[-1-bit//8]^=1<<(bit%8); return bytes(t)

def pack(result,trace): return {'result':result,'trace':trace}

EXTRA = {}

def run(p):
    s=exact(p['plaintext'],16);k=b(p['key']);bit=n(p['bit']);c,t=aes(s,k);d,u=aes(bitflip(s,bit),k);e,w=aes(s,bitflip(k,bit));r=[]
    for a,b0,c0 in zip(t,u,w):
        if not a['step'].endswith('AddRoundKey'): continue
        x=hamming(b(a['state']),b(b0['state']));y=hamming(b(a['state']),b(c0['state']));r.append(row(a['step'],base=a['state'],plaintext_flip=b0['state'],key_flip=c0['state'],plaintext_bits=x,key_bits=y,plaintext_pct=100*x/128,key_pct=100*y/128))
    return pack({'plaintext_bits':hamming(c,d),'key_bits':hamming(c,e)},r)

PARAMS = {'plaintext': '0123456789ABCDEFFEDCBA9876543210', 'key': '0F1571C947D9E8590CB7ADD6AF7F6798', 'bit': '120'}
EXPECTED = {'plaintext_bits': 58, 'key_bits': 53}
ALT = {'plaintext': '0123456789ABCDEFFEDCBA9876543210', 'key': '0F1571C947D9E8590CB7ADD6AF7F6798', 'bit': '7'}
ALT_EXPECTED = {'plaintext_bits': 73, 'key_bits': 71}

if __name__ == "__main__":
    import argparse, json
    parser=argparse.ArgumentParser(description="CR20 synthetic cryptography exercise")
    parser.add_argument("--params", help="JSON parameter override file")
    parser.add_argument("--test", action="store_true")
    args=parser.parse_args()
    if args.test:
        assert run(PARAMS)["result"] == EXPECTED
        assert run(ALT)["result"] == ALT_EXPECTED
        print("CR20 default and changed input passed")
    else:
        parameters=PARAMS if not args.params else {**PARAMS,**json.load(open(args.params))}
        print(json.dumps(run(parameters),indent=2))
Verified default result
Reference result · json
{
  "plaintext_bits": 58,
  "key_bits": 53
}

05 · Interactive flashcards

Recall before revealing. Review and mastery ratings remain on this device.

Browse all explanations
Why should DES and AES distances be normalized?

Their state sizes differ (64 vs 128 bits).

What is the dependent variable in this lab?

Hamming distance and percentage in every corresponding round

What must remain controlled?

base plaintext, key and round configuration

What input settings define the baseline for this experiment?

plaintext = 0123456789ABCDEFFEDCBA9876543210; key = 0F1571C947D9E8590CB7ADD6AF7F6798; bit = 120

What is the first intermediate state in the baseline?

step: 0 AddRoundKey; base: 0E3634AECE7225B6F26B174ED92B5588; plaintext_flip: 0F3634AECE7225B6F26B174ED92B5588; key_flip: 0F3634AECE7225B6F26B174ED92B5588; plaintext_bits: 1

What does a highlighted byte mean?

At least one bit differs; it does not imply eight changed bits.

Must avalanche distance increase every round?

No; distance is a measured count and can decrease.

Why compare plaintext and key flips separately?

To isolate the independent variable and measure its effect.

06 · Knowledge assessment

Formative check

Which denominator converts AES state Hamming distance to a percentage?

Responses are for instructor review; no grading key is provided here.

Independent assessment

Reproduce the reference baseline at bit 120. Repeat at bit 7 and 31; tabulate distances for rounds 1, 5 and 10 and explain why these samples are not a security proof. Use an additional valid trial, a calculation or a counterexample to support your reasoning. Submit evidence from both runtimes and explain what the experiment does not establish.

Part F · Engineering evidence record

Record the baseline, prediction, changed input, observed result, discrepancy and limitation. Save locally or export with the displayed result. This is not an official submission.

All Cryptography Engineering labsNext laboratory · CR21 →

How to investigate · CR20

Independent variable: bit 120 (worked example), then 0, 7 and 15 in separate runs.

Controlled variables: base plaintext, key and round configuration.

Dependent evidence: Hamming distance and percentage in every corresponding round.

Weak conclusion: “The output changed.” Stronger reasoning: cite both measured values, name the transformation responsible, and state why the observation does or does not generalize.

Dr. Mohammad · CR20

Offline, deterministic, current-step tutoring. No external AI service or real hardware access.