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 · CR22 · MODES
IoT Security and Privacy

AES-CBC · block processing and errors

\(C_{i}\)=E(K,\(P_{i}\) XOR \(C_{i-1}\)), with \(C_{0}\)=IV.

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

Scope and objectives

Scope of the experiment

CBC mixes each plaintext block with the preceding ciphertext before encryption, starting from an unpredictable IV. Decryption needs the preceding ciphertext, not preceding plaintext.

The focus of this experiment is to trace CBC IV initialization and ciphertext chaining. Students then calculate XOR inputs and predict corrupted-ciphertext effects, and verify decryption and distinguish chaining from authentication. 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 CBC IV initialization and ciphertext chaining.
  • Calculate XOR inputs and predict corrupted-ciphertext effects.
  • Verify decryption and distinguish chaining from authentication.
  • 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 CBC IV initialization and ciphertext chaining, calculate XOR inputs and predict corrupted-ciphertext effects, and verify decryption and distinguish chaining from authentication.

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 decryption and distinguish chaining from authentication. 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-CFB · 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

CR22 · AES-CBC · block processing and errors

CBC XORs \(P_{i}\) with \(C_{i-1}\) before encryption; \(C_{0}\) is the IV. During decryption, decrypt \(C_{i}\) 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.

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

CBC XORs \(P_{i}\) with \(C_{i-1}\) before encryption; \(C_{0}\) is the IV. During decryption, decrypt \(C_{i}\) 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.

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.

CBC chaining

1 · Principles and purpose

CBC mixes each plaintext block with the preceding ciphertext before encryption, starting from an unpredictable IV. Decryption needs the preceding ciphertext, not preceding plaintext.

2 · Mathematical and algorithmic foundations

C0=IV; \(C_{i}\)=E_K(\(P_{i}\)⊕\(C_{i-1}\)); \(P_{i}\)=D_K(\(C_{i}\))⊕\(C_{i-1}\). Encryption is serial; decryption can parallelize with ciphertext available. Padding is needed for incomplete blocks.

3 · Worked teaching example

A flipped bit in C1 makes recovered P1 generally unpredictable and flips the corresponding bit in P2, while P3 is unaffected. The IV is not secret but its integrity and correct generation matter. CBC alone is unauthenticated.

Verified default trace · 7 intermediate states

Given parameters (teaching example):

{
  "plaintext": "6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A",
  "key": "2B7E151628AED2A6ABF7158809CF4F3C",
  "iv": "000102030405060708090A0B0C0D0E0F",
  "flip_byte": "0"
}
StageComputed values
1{ "step": "Block/segment 1", "input": "6BC1BEE22E409F96E93D7E117393172A", "register": "000102030405060708090A0B0C0D0E0F", "cipher_input": "6BC0BCE12A459991E134741A7F9E1925", "keystream": "", "output": "7649ABAC8119B246CEE98E9B12E9197D", "next_register": "7649ABAC8119B246CEE98E9B12E9197D" }
2{ "step": "Block/segment 2", "input": "6BC1BEE22E409F96E93D7E117393172A", "register": "7649ABAC8119B246CEE98E9B12E9197D", "cipher_input": "1D88154EAF592DD027D4F08A617A0E57", "keystream": "", "output": "4CBBC858756B358125529E9698A38F44", "next_register": "4CBBC858756B358125529E9698A38F44" }
3{ "step": "Block/segment 3", "input": "6BC1BEE22E409F96E93D7E117393172A", "register": "4CBBC858756B358125529E9698A38F44", "cipher_input": "277A76BA5B2BAA17CC6FE087EB30986E", "keystream": "", "output": "9F6F0796EE3E47B0D87C761B20527F78", "next_register": "9F6F0796EE3E47B0D87C761B20527F78" }
4{ "step": "Decrypt Block/segment 1", "input": "7649ABAC8119B246CEE98E9B12E9197D", "register": "000102030405060708090A0B0C0D0E0F", "cipher_input": "6BC0BCE12A459991E134741A7F9E1925", "keystream": "", "output": "6BC1BEE22E409F96E93D7E117393172A", "next_register": "7649ABAC8119B246CEE98E9B12E9197D" }
5{ "step": "Decrypt Block/segment 2", "input": "4CBBC858756B358125529E9698A38F44", "register": "7649ABAC8119B246CEE98E9B12E9197D", "cipher_input": "1D88154EAF592DD027D4F08A617A0E57", "keystream": "", "output": "6BC1BEE22E409F96E93D7E117393172A", "next_register": "4CBBC858756B358125529E9698A38F44" }
6{ "step": "Decrypt Block/segment 3", "input": "9F6F0796EE3E47B0D87C761B20527F78", "register": "4CBBC858756B358125529E9698A38F44", "cipher_input": "277A76BA5B2BAA17CC6FE087EB30986E", "keystream": "", "output": "6BC1BEE22E409F96E93D7E117393172A", "next_register": "9F6F0796EE3E47B0D87C761B20527F78" }
7{ "step": "Tamper", "byte": 0, "changed_bits": [ 68, 1, 0 ] }

Recorded result

{
  "ciphertext": "7649ABAC8119B246CEE98E9B12E9197D4CBBC858756B358125529E9698A38F449F6F0796EE3E47B0D87C761B20527F78",
  "recovered": "6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A",
  "error_bits_by_block": [
    68,
    1,
    0
  ],
  "length": 48
}

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

CBC chaining

IV initializes the chain, P_i is plaintext, C_i ciphertext. The preceding ciphertext must be available for decryption; encryption is sequential. A secure CBC configuration also needs integrity protection.

\[C_0=IV,\qquad C_i=E_K(P_i\oplus C_{i-1}),\qquad P_i=D_K(C_i)\oplus C_{i-1}\]

Concept animation · CBC ciphertext chaining

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.

CBC — block dependency and encryptionBlock 1Plaintext6BC1BEE2IV / previous C00010203⊕AES encrypt6BC0BCE1Ciphertext7649ABAC8119…Block 2Plaintext6BC1BEE2IV / previous C7649ABAC⊕AES encrypt1D88154ECiphertext4CBBC858756B…Block 3Plaintext6BC1BEE2IV / previous C4CBBC858⊕AES encrypt277A76BACiphertext9F6F0796EE3E…Ciphertext feeds the next XOR before encryption.CBC — block dependency and encryptionBlock 1Plaintext6BC1BEE2IV / previous C00010203⊕AES encrypt6BC0BCE1Ciphertext7649ABAC8119…Block 2Plaintext6BC1BEE2IV / previous C7649ABAC⊕AES encrypt1D88154ECiphertext4CBBC858756B…Block 3Plaintext6BC1BEE2IV / previous C4CBBC858⊕AES encrypt277A76BACiphertext9F6F0796EE3E…Ciphertext feeds the next XOR before encryption.CBC — block dependency and encryptionBlock 1Plaintext6BC1BEE2IV / previous C00010203⊕AES encrypt6BC0BCE1Ciphertext7649ABAC8119…Block 2Plaintext6BC1BEE2IV / previous C7649ABAC⊕AES encrypt1D88154ECiphertext4CBBC858756B…Block 3Plaintext6BC1BEE2IV / previous C4CBBC858⊕AES encrypt277A76BACiphertext9F6F0796EE3E…Ciphertext feeds the next XOR before encryption.

Step 1 of 3 · Block/segment 1

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

Block/segment 1

input
6BC1BEE22E409F96E93D7E117393172A
register
000102030405060708090A0B0C0D0E0F
cipher_input
6BC0BCE12A459991E134741A7F9E1925
keystream
output
7649ABAC8119B246CEE98E9B12E9197D
next_register
7649ABAC8119B246CEE98E9B12E9197D
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.
CBC · Block/segment 1Plaintext Pᵢ6BC1BEE22E409F96E93D7E117393172APrevious C / IV000102030405060708090A0B0C0D0E0FPᵢ XOR register6BC0BCE12A459991E134741A7F9E1925AES encrypt → Cᵢ7649ABAC8119B246CEE98E9B12E9197DFeed Cᵢ forward7649ABAC8119B246CEE98E9B12E9197DCBC chains ciphertext; the IV starts the first block.

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 a step to inspect the current calculation. The blue workbench matches the established instrument palette. Exact numeric values are also listed in the trace; scroll diagrams horizontally on narrow displays.

Calculated result

{
  "ciphertext": "7649ABAC8119B246CEE98E9B12E9197D4CBBC858756B358125529E9698A38F449F6F0796EE3E47B0D87C761B20527F78",
  "recovered": "6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A",
  "error_bits_by_block": [
    68,
    1,
    0
  ],
  "length": 48
}
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

\(C_{i}\)=E(K,\(P_{i}\) XOR \(C_{i-1}\)), with \(C_{0}\)=IV. Decrypt D(K,\(C_{i}\)) XOR \(C_{i-1}\). IV must be unpredictable and protected against modification; not secret. Whole blocks or padding. A ciphertext error corrupts its plaintext block and flips matching bits in next. Confidentiality only; does not authenticate data.

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

Using the baseline CBC plaintext and IV, compute P1 XOR IV byte by byte. Use the provided AES block function for C1 and compute P2 XOR C1. Predict the effect of corrupting a ciphertext bit on the first and second recovered blocks.

02 · XOR tracing

XOR tracing · Independent work

In CBC, first plaintext byte=0xA5 and IV byte=0x3C. Compute byte entering AES. If first ciphertext byte is altered by mask 0x04, what bit change occurs in next plaintext block?

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

For the separate teaching-test configuration plaintext: 6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A; key: 2B7E151628AED2A6ABF7158809CF4F3C; iv: 000102030405060708090A0B0C0D0E0F; flip_byte: 16, predict length 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 · CR22-02

A teaching trace for AES-CBC · block processing and errors contains step: Block/segment 2; input: 6BC1BEE22E409F96E93D7E117393172A; register: 7649ABAC8119B246CEE98E9B12E9197D; cipher_input: 1D88154EAF592DD027D4F08A617A0E57; keystream: . Explain the role of next_register (recorded value 4CBBC858756B358125529E9698A38F44) 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 · CR22-03

The first teaching trace contains step: Block/segment 1; input: 6BC1BEE22E409F96E93D7E117393172A; register: 000102030405060708090A0B0C0D0E0F; cipher_input: 6BC0BCE12A459991E134741A7F9E1925; keystream: ; output: 7649ABAC8119B246CEE98E9B12E9197D; next_register: 7649ABAC8119B246CEE98E9B12E9197D; the last contains step: Tamper; byte: 0; changed_bits: [68, 1, 0]. 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 · CR22-04

Plan a comparison of plaintext: 6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A; key: 2B7E151628AED2A6ABF7158809CF4F3C; iv: 000102030405060708090A0B0C0D0E0F; flip_byte: 0 with plaintext: 6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A; key: 2B7E151628AED2A6ABF7158809CF4F3C; iv: 000102030405060708090A0B0C0D0E0F; flip_byte: 16. Record the dependent value error_bits_by_block, 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

Trace CBC chaining and two-block error propagation

  1. Write a prediction using the worked calculation in Concepts.
  2. Trace each block input, previous ciphertext, XOR and encryption output. Select decryption step 4 and verify its XOR reverses the first block. Record the Tamper step.
  3. Export the trace and compare against the reference after recording your prediction.

Experimental inputs

Experimental reference · json
{"plaintext":"6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A","key":"2B7E151628AED2A6ABF7158809CF4F3C","iv":"000102030405060708090A0B0C0D0E0F","flip_byte":"0"}
Verified baseline reference (check after predicting)
Experimental reference · json
{"ciphertext":"7649ABAC8119B246CEE98E9B12E9197D4CBBC858756B358125529E9698A38F449F6F0796EE3E47B0D87C761B20527F78","recovered":"6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A","error_bits_by_block":[68,1,0],"length":48}

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

IV, XOR input, ciphertexts \(C_{1}\)–\(C_{3}\), error bits per block, and recovered plaintext.

Run baseline →
02

Part D · Controlled experiment — Trace CBC chaining and two-block error propagation

  1. Change flip_byte to 16; then restore 0 and change the first IV byte from 00 to 80. Keep plaintext and key fixed. Compare changed ciphertext and error distribution.
  2. Record all fixed settings and complete the trial table.
  3. Measure IV, XOR input, ciphertexts \(C_{1}\)–\(C_{3}\), error bits per block, and recovered plaintext. Compare against the baseline and explain the mechanism.
TrialInput configurationPredictionObservedVerification
1{"plaintext":"6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A","key":"2B7E151628AED2A6ABF7158809CF4F3C","iv":"000102030405060708090A0B0C0D0E0F","flip_byte":"0"}
2{"plaintext":"6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A","key":"2B7E151628AED2A6ABF7158809CF4F3C","iv":"000102030405060708090A0B0C0D0E0F","flip_byte":"16"}
3{"plaintext":"6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A","key":"2B7E151628AED2A6ABF7158809CF4F3C","iv":"800102030405060708090A0B0C0D0E0F","flip_byte":"0"}

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. Run each assigned trial in the notebook or edit a copy of example-input.json and use python3 lab.py --params example-input.json. Compare the exact corresponding states.
  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 flip_byte 0 to 16; change one byte of plaintext. First verified alternate: {"flip_byte": "16"}.
  3. Keep key and IV/counter; keep segment fixed unless investigating CFB.
  4. Measure each block/segment, register, ciphertext, recovered block and tamper distance.
  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 CR22
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 CR22/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": "Block/segment 1",
    "input": "6BC1BEE22E409F96E93D7E117393172A",
    "register": "000102030405060708090A0B0C0D0E0F",
    "cipher_input": "6BC0BCE12A459991E134741A7F9E1925",
    "keystream": "",
    "output": "7649ABAC8119B246CEE98E9B12E9197D",
    "next_register": "7649ABAC8119B246CEE98E9B12E9197D"
  },
  "result": {
    "ciphertext": "7649ABAC8119B246CEE98E9B12E9197D4CBBC858756B358125529E9698A38F449F6F0796EE3E47B0D87C761B20527F78",
    "recovered": "6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A",
    "error_bits_by_block": [
      68,
      1,
      0
    ],
    "length": 48
  }
}

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
# ============================================================
# CR22 | 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

# Use the selected chaining/feedback/counter rule and trace every block.
def modes(data,key,iv,mode,dec=False,segment=16):
    out=b''; trace=[]; state=iv
    if mode in ('ECB','CBC') and len(data)%16: raise ValueError('ECB/CBC require whole blocks; apply padding separately')
    if mode=='CFB' and not 1<=segment<=16: raise ValueError('CFB segment 1–16 bytes')
    step=segment if mode=='CFB' else 16
    for i in range(0,len(data),step):
        b=data[i:i+step]; old=state; stream=b''; mixed=b
        if mode=='ECB': c=aes(b,key,dec)[0]
        elif mode=='CBC':
            if dec: mixed=aes(b,key,True)[0]; c=xor(mixed,state); state=b
            else: mixed=xor(b,state); c=aes(mixed,key)[0]; state=c
        elif mode=='CTR':
            stream=aes(state,key)[0]; c=xor(b,stream); state=((int.from_bytes(state,'big')+1)%(1<<128)).to_bytes(16,'big')
        else:
            stream=aes(state,key)[0]; c=xor(b,stream)
            state=stream if mode=='OFB' else state[len(b):]+(b if dec else c)
        out+=c; trace.append(row(f'Block/segment {i//step+1}',input=hexs(b),register=hexs(old) if mode!='ECB' else 'none',cipher_input=hexs(mixed),keystream=hexs(stream),output=hexs(c),next_register=hexs(state) if mode!='ECB' else 'none'))
    return out,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 pack(result,trace): return {'result':result,'trace':trace}

EXTRA = {'mode': 'CBC'}

def run(p):
    s=b(p['plaintext']);k=b(p['key']);mode=EXTRA['mode'];iv=exact(p.get('iv','00'*16),16);seg=n(p.get('segment','16'));flip=n(p['flip_byte']);c,t=modes(s,k,iv,mode,segment=seg);d,u=modes(c,k,iv,mode,True,seg)
    if not 0<=flip<len(c): raise ValueError('Flip byte outside ciphertext')
    bad=bytearray(c);bad[flip]^=1; e,w=modes(bytes(bad),k,iv,mode,True,seg);err=[hamming(s[i:i+16],e[i:i+16]) for i in range(0,len(s),16)]
    return pack({'ciphertext':hexs(c),'recovered':hexs(d),'error_bits_by_block':err,'length':len(c)},t+[dict(x,step='Decrypt '+x['step']) for x in u]+[row('Tamper',byte=flip,changed_bits=err)])

PARAMS = {'plaintext': '6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A', 'key': '2B7E151628AED2A6ABF7158809CF4F3C', 'iv': '000102030405060708090A0B0C0D0E0F', 'flip_byte': '0'}
EXPECTED = {'ciphertext': '7649ABAC8119B246CEE98E9B12E9197D4CBBC858756B358125529E9698A38F449F6F0796EE3E47B0D87C761B20527F78', 'recovered': '6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A', 'error_bits_by_block': [68, 1, 0], 'length': 48}
ALT = {'plaintext': '6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A', 'key': '2B7E151628AED2A6ABF7158809CF4F3C', 'iv': '000102030405060708090A0B0C0D0E0F', 'flip_byte': '16'}
ALT_EXPECTED = {'ciphertext': '7649ABAC8119B246CEE98E9B12E9197D4CBBC858756B358125529E9698A38F449F6F0796EE3E47B0D87C761B20527F78', 'recovered': '6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A', 'error_bits_by_block': [0, 63, 1], 'length': 48}

if __name__ == "__main__":
    import argparse, json
    parser=argparse.ArgumentParser(description="CR22 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("CR22 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
{
  "ciphertext": "7649ABAC8119B246CEE98E9B12E9197D4CBBC858756B358125529E9698A38F449F6F0796EE3E47B0D87C761B20527F78",
  "recovered": "6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A",
  "error_bits_by_block": [
    68,
    1,
    0
  ],
  "length": 48
}

05 · Interactive flashcards

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

Browse all explanations
Can the next block be decrypted independently?

Yes if its preceding ciphertext block is available.

What is the dependent variable in this lab?

each block/segment, register, ciphertext, recovered block and tamper distance

What must remain controlled?

key and IV/counter; keep segment fixed unless investigating CFB

What input settings define the baseline for this experiment?

plaintext = 6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A6BC1BEE22E409F96E93D7E117393172A; key = 2B7E151628AED2A6ABF7158809CF4F3C; iv = 000102030405060708090A0B0C0D0E0F; flip_byte = 0

What is the first intermediate state in the baseline?

step: Block/segment 1; input: 6BC1BEE22E409F96E93D7E117393172A; register: 000102030405060708090A0B0C0D0E0F; cipher_input: 6BC0BCE12A459991E134741A7F9E1925; keystream:

What is C₀?

The IV.

Why is CBC decryption parallelizable?

All ciphertext blocks and their predecessors are available.

Should a CBC IV be secret?

No, but unpredictable for encryption and protected against modification.

06 · Knowledge assessment

Formative check

What happens when a bit of \(C_{1}\) is flipped in CBC?

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

Independent assessment

Using the same 48-byte plaintext, change IV byte 0 from 00 to FF and compare all three ciphertext blocks. Restore IV, flip a byte in ciphertext block 2 and calculate the decryption error by block. 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 · CR23 →

How to investigate · CR22

Independent variable: flip_byte 0 to 16; change one byte of plaintext.

Controlled variables: key and IV/counter; keep segment fixed unless investigating CFB.

Dependent evidence: each block/segment, register, ciphertext, recovered block and tamper distance.

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

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