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 · CR17 · AES
IoT Security and Privacy

AES · AddRoundKey

State and round key are 16-byte column-major arrays.

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

Scope and objectives

Scope of the experiment

AddRoundKey injects secret-dependent material into the state. The round key is a 128-bit slice of the expanded key, aligned column-major.

The focus of this experiment is to trace state and round-key byte alignment. Students then calculate AddRoundKey as sixteen XOR operations, and verify that applying the same key again recovers the input. 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

  • Trace state and round-key byte alignment.
  • Calculate AddRoundKey as sixteen XOR operations.
  • Verify that applying the same key again recovers the input.
  • 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 trace state and round-key byte alignment, calculate AddRoundKey as sixteen XOR operations, and verify that applying the same key again recovers the input.

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 verify that applying the same key again recovers the input. 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 · key expansion.

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

CR17 · AES · AddRoundKey

State and round key are 16-byte column-major arrays. XOR corresponding bytes; applying the same key again recovers the state. It is the only round transformation directly using secret-key material.

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

State and round key are 16-byte column-major arrays. XOR corresponding bytes; applying the same key again recovers the state. It is the only round transformation directly using secret-key material.

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.

Round-key addition

1 · Principles and purpose

AddRoundKey injects secret-dependent material into the state. The round key is a 128-bit slice of the expanded key, aligned column-major.

2 · Mathematical and algorithmic foundations

S′[r,c]=S[r,c]⊕RK[r,c]. Applying the same XOR twice is the inverse. SubBytes and diffusion are essential because XOR alone is linear.

3 · Worked teaching example

0x57⊕0x83=D4; D4⊕83=57. One byte changes only corresponding positions at this step; the later nonlinear and diffusion layers spread changes.

Verified default trace · 18 intermediate states

Given parameters (teaching example):

{
  "state": "00112233445566778899AABBCCDDEEFF",
  "key": "000102030405060708090A0B0C0D0E0F"
}
StageComputed values
1{ "step": "Byte 0", "state": "00", "key": "00", "output": "00" }
2{ "step": "Byte 1", "state": "11", "key": "01", "output": "10" }
3{ "step": "Byte 2", "state": "22", "key": "02", "output": "20" }
4{ "step": "Byte 3", "state": "33", "key": "03", "output": "30" }
5{ "step": "Byte 4", "state": "44", "key": "04", "output": "40" }
6{ "step": "Byte 5", "state": "55", "key": "05", "output": "50" }
7{ "step": "Byte 6", "state": "66", "key": "06", "output": "60" }
8{ "step": "Byte 7", "state": "77", "key": "07", "output": "70" }
9{ "step": "Byte 8", "state": "88", "key": "08", "output": "80" }
10{ "step": "Byte 9", "state": "99", "key": "09", "output": "90" }
11{ "step": "Byte 10", "state": "AA", "key": "0A", "output": "A0" }
12{ "step": "Byte 11", "state": "BB", "key": "0B", "output": "B0" }
13{ "step": "Byte 12", "state": "CC", "key": "0C", "output": "C0" }
14{ "step": "Byte 13", "state": "DD", "key": "0D", "output": "D0" }
15{ "step": "Byte 14", "state": "EE", "key": "0E", "output": "E0" }
16{ "step": "Byte 15", "state": "FF", "key": "0F", "output": "F0" }
17{ "step": "Output matrix", "state": "00102030405060708090A0B0C0D0E0F0" }
18{ "step": "Inverse", "state": "00112233445566778899AABBCCDDEEFF" }

Recorded result

{
  "output": "00102030405060708090A0B0C0D0E0F0",
  "recovered": "00112233445566778899AABBCCDDEEFF"
}

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

Round-key addition

S and K_r are equal-size 128-bit states. The inverse is the same XOR operation. The original key length may exceed the round-key length.

\[S\,^{\prime}=S\oplus K_r,\qquad S=S\,^{\prime}\oplus K_r\]

Concept animation · AES state transformation

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.

AES · AddRoundKey: AES state transformationAES column-major state004080C0105090D02060A0E03070B0F0Highlighted bytes changed from the preceding recorded state.

Step 1 of 2 · Output matrix

Output matrix

State hex
00102030405060708090A0B0C0D0E0F0
Ordering
column-major

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

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.
CR17 Byte 1AddRoundKey · byte-wise XOR, no carryInput004488CC115599DD2266AAEE3377BBFFRound key0004080C0105090D02060A0E03070B0FOutput004080C0105090D02060A0E03070B0F0⊕=11 ⊕ 01 = 1000010001 ⊕ 00000001 = 00010000XOR with the same round key a second time restores the original byte.

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

{
  "output": "00102030405060708090A0B0C0D0E0F0",
  "recovered": "00112233445566778899AABBCCDDEEFF"
}
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

State and round key are 16-byte column-major arrays. XOR corresponding bytes; applying the same key again recovers the state. It is the only round transformation directly using secret-key material.

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

Take state bytes 00 through 0F and key bytes 0F through 00, both in column-major order. Calculate all 16 XOR values; repeat with the same key to recover the input. Explain why the operation alone is insufficient for encryption.

02 · Reverse reasoning

Reverse reasoning · Independent work

State byte 0xA6 becomes 0x3C after AddRoundKey. Determine the key byte and verify both directions.

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 · CR17-01

For the separate teaching-test configuration state: 00112233445566778899AABBCCDDEEFF; key: FF0102030405060708090A0B0C0D0E0F, predict output 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 · CR17-02

A teaching trace for AES · AddRoundKey contains step: Byte 1; state: 11; key: 01; output: 10. Explain the role of output (recorded value 10) and identify the rule or input that determines it. Distinguish an intermediate state from the final result.

Advanced · Identify a terminal invariant

Independent theoretical exercise · CR17-03

The first teaching trace contains step: Byte 0; state: 00; key: 00; output: 00; the last contains step: Inverse; state: 00112233445566778899AABBCCDDEEFF. Identify one distinction between the initial operation and completion. What additional condition must hold to use the result?

Challenging · Controlled algorithm verification

Independent theoretical exercise · CR17-04

Plan a comparison of state: 00112233445566778899AABBCCDDEEFF; key: 000102030405060708090A0B0C0D0E0F with state: 00112233445566778899AABBCCDDEEFF; key: FF0102030405060708090A0B0C0D0E0F. Record the dependent value output, 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

Byte-level XOR and reversible key injection

  1. Write a prediction using the worked calculation in Concepts.
  2. Load the baseline state and round key. Select byte 1 and trace both binary operands and output. Select bytes 0, 6 and 15 and reproduce them manually. Select the final Inverse step.
  3. Export the trace and compare against the reference only after predicting.

Experimental inputs

Experimental reference · json
{"state":"00112233445566778899AABBCCDDEEFF","key":"000102030405060708090A0B0C0D0E0F"}
Verified baseline reference (check after predicting)
Experimental reference · json
{"output":"00102030405060708090A0B0C0D0E0F0","recovered":"00112233445566778899AABBCCDDEEFF"}

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

Byte index, original state and key in binary, XOR output, changed output bits, recovered state.

Run baseline →
02

Part D · Controlled experiment — Byte-level XOR and reversible key injection

  1. Keep the state fixed; change key byte 0 from 00 to FF, then from 00 to 01 in a separate run. Compare output Hamming distances and verify unchanged other bytes.
  2. Record the conditions held constant and complete the trial table.
  3. Measure Byte index, original state and key in binary, XOR output, changed output bits, recovered state. Explain the first differing operation and verify inverse recovery where applicable.
TrialInput configurationPredictionObservedVerification
1{"state":"00112233445566778899AABBCCDDEEFF","key":"000102030405060708090A0B0C0D0E0F"}
2{"state":"00112233445566778899AABBCCDDEEFF","key":"FF0102030405060708090A0B0C0D0E0F"}
3{"state":"00112233445566778899AABBCCDDEEFF","key":"010102030405060708090A0B0C0D0E0F"}

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 key byte 0 from 00 to FF. First verified alternate: {"key": "FF0102030405060708090A0B0C0D0E0F"}.
  3. Keep state and remaining key bytes.
  4. Measure all sixteen byte XORs and recovered state.
  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 CR17
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 CR17/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": "Byte 0",
    "state": "00",
    "key": "00",
    "output": "00"
  },
  "result": {
    "output": "00102030405060708090A0B0C0D0E0F0",
    "recovered": "00112233445566778899AABBCCDDEEFF"
  }
}

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
# ============================================================
# CR17 | Educational implementation and trace functions
# Copyright © 2026/2027 Dr. Mohammad Alja’afreh
# PSUT IoT Engineering Studio | Educational, synthetic inputs
# ============================================================
def hx(n,w=2): return f'{n:0{w}X}'

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}

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 pack(result,trace): return {'result':result,'trace':trace}

EXTRA = {}

def run(p):
    s=exact(p['state'],16);k=exact(p['key'],16);o=xor(s,k);return pack({'output':hexs(o),'recovered':hexs(xor(o,k))},[row(f'Byte {i}',state=hx(x),key=hx(y),output=hx(z)) for i,(x,y,z) in enumerate(zip(s,k,o))]+[row('Output matrix',state=hexs(o)),row('Inverse',state=hexs(xor(o,k)))])

PARAMS = {'state': '00112233445566778899AABBCCDDEEFF', 'key': '000102030405060708090A0B0C0D0E0F'}
EXPECTED = {'output': '00102030405060708090A0B0C0D0E0F0', 'recovered': '00112233445566778899AABBCCDDEEFF'}
ALT = {'state': '00112233445566778899AABBCCDDEEFF', 'key': 'FF0102030405060708090A0B0C0D0E0F'}
ALT_EXPECTED = {'output': 'FF102030405060708090A0B0C0D0E0F0', 'recovered': '00112233445566778899AABBCCDDEEFF'}

if __name__ == "__main__":
    import argparse, json
    parser=argparse.ArgumentParser(description="CR17 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("CR17 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
{
  "output": "00102030405060708090A0B0C0D0E0F0",
  "recovered": "00112233445566778899AABBCCDDEEFF"
}

05 · Interactive flashcards

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

Browse all explanations
Why is XOR reversible with the same operand?

(a XOR k) XOR k=a.

What is the dependent variable in this lab?

all sixteen byte XORs and recovered state

What must remain controlled?

state and remaining key bytes

What input settings define the baseline for this experiment?

state = 00112233445566778899AABBCCDDEEFF; key = 000102030405060708090A0B0C0D0E0F

What is the first intermediate state in the baseline?

step: Byte 0; state: 00; key: 00; output: 00

Why is AddRoundKey invertible?

(s XOR k) XOR k = s.

How many bits change at this step when exactly one round-key bit changes?

Exactly one.

Does a 256-bit AES key imply a 256-bit round key?

No; each round key is 128 bits.

06 · Knowledge assessment

Formative check

Which operation reverses AddRoundKey?

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

Independent assessment

Use plaintext 11111111111111111111111111111111 and key 00112233445566778899AABBCCDDEEFF; calculate byte 5 and byte 15 of AddRoundKey and prove inverse recovery. 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 · CR18 →

How to investigate · CR17

Independent variable: key byte 0 from 00 to FF.

Controlled variables: state and remaining key bytes.

Dependent evidence: all sixteen byte XORs and recovered state.

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 · CR17

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