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 · CR27 · STORAGE
IoT Security and Privacy

XTS-AES · sector tweaks and ciphertext stealing

XTS uses two distinct AES keys: \(T_{0}\)=E(\(K_{2}\), sector encoded little-endian); \(T_{j+1}\)=α\(T_{j}\) in \(\mathrm{GF}(2^{128})\).

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

Scope and objectives

Scope of the experiment

XTS uses two independent AES keys. The tweak binds encryption to a storage data-unit identifier and block position; unlike a network nonce, this design targets sector confidentiality.

The focus of this experiment is to trace XTS data-unit tweak derivation and finite-field update. Students then explain ciphertext stealing for partial final blocks, and verify sector recovery and distinguish storage confidentiality 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 XTS data-unit tweak derivation and finite-field update.
  • Explain ciphertext stealing for partial final blocks.
  • Verify sector recovery and distinguish storage confidentiality 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 XTS data-unit tweak derivation and finite-field update, explain ciphertext stealing for partial final blocks, and verify sector recovery and distinguish storage confidentiality 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 sector recovery and distinguish storage confidentiality 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 Block ciphers · architecture and fair comparison.

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

CR27 · XTS-AES · sector tweaks and ciphertext stealing

XTS uses two separate AES keys. \(T_{0}\) = E(\(K_{2}\), little-endian sector identifier), and successive tweaks multiply by α in \(\mathrm{GF}(2^{128})\). A full block is transformed by C = E(\(K_{1}\),P XOR T) XOR T. For a short final block, ciphertext stealing rearranges bytes from the provisional penultimate block so the sector length is preserved. Decryption reverses these operations. XTS provides storage confidentiality, not message authentication.

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

XTS uses two separate AES keys. \(T_{0}\) = E(\(K_{2}\), little-endian sector identifier), and successive tweaks multiply by α in \(\mathrm{GF}(2^{128})\). A full block is transformed by C = E(\(K_{1}\),P XOR T) XOR T. For a short final block, ciphertext stealing rearranges bytes from the provisional penultimate block so the sector length is preserved. Decryption reverses these operations. XTS provides storage confidentiality, not message authentication.

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.

XTS storage encryption

1 · Principles and purpose

XTS uses two independent AES keys. The tweak binds encryption to a storage data-unit identifier and block position; unlike a network nonce, this design targets sector confidentiality.

2 · Mathematical and algorithmic foundations

T0=E_K2(data-unit identifier); \(T_{j+1}\)=α·\(T_{j}\) in \(\mathrm{GF}(2^{128})\). \(C_{j}\)=E_K1(\(P_{j}\)⊕\(T_{j}\))⊕\(T_{j}\). For a partial final block, ciphertext stealing rearranges the preceding full-block output and uses the next tweak.

\[C_j=E_{K_1}(P_j\oplus T_j)\oplus T_j,\qquad T_{j+1}=\alpha T_j\]

3 · Worked teaching example

A data unit must contain at least one full block. Inspect the two final stages in the trace and verify length preservation and decryption. XTS does not independently authenticate sectors.

Verified default trace · 2 intermediate states

Given parameters (teaching example):

{
  "plaintext": "00112233445566778899AABBCCDDEEFF1122334455",
  "key": "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F",
  "sector": "7"
}
StageComputed values
1{ "step": "Ciphertext stealing", "tweak": "F7D73FDACC0B64382D81CF8EDC9C338A", "next_tweak": "69AF7FB49917C8705A029F1DB9396714", "full": "219BF750510C5D9F0DE3A9630D29B7FC", "partial": "96ABE5533D" }
2{ "step": "Decrypt Ciphertext stealing", "tweak": "F7D73FDACC0B64382D81CF8EDC9C338A", "next_tweak": "69AF7FB49917C8705A029F1DB9396714", "full": "00112233445566778899AABBCCDDEEFF", "partial": "1122334455" }

Recorded result

{
  "ciphertext": "219BF750510C5D9F0DE3A9630D29B7FC96ABE5533D",
  "recovered": "00112233445566778899AABBCCDDEEFF1122334455",
  "length": 21
}

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

XTS full-block transform

I is the encoded data-unit identifier. Multiplication is in \(\mathrm{GF}(2^{128})\) under the XTS convention. The partial last block uses ciphertext stealing, not zero padding. XTS does not provide integrity.

\[T_j=\alpha^j\otimes E_{K_2}(I),\qquad C_j=E_{K_1}(P_j\oplus T_j)\oplus T_j\]

Concept animation · independent state notebook

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.

XTS-AES · sector tweaks and ciphertext stealing: independent state notebook12Ciphertext stealingtweakF7D73FDACC0B64382D81CF8EDC9C338Anext_tweak69AF7FB49917C8705A029F1DB9396714full219BF750510C5D9F0DE3A9630D29B7FCpartial96ABE5533D

Step 1 of 2 · Ciphertext stealing

Ciphertext stealing

step
Ciphertext stealing
tweak
F7D73FDACC0B64382D81CF8EDC9C338A
next_tweak
69AF7FB49917C8705A029F1DB9396714
full
219BF750510C5D9F0DE3A9630D29B7FC
partial
96ABE5533D

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.
XTS-AES · Ciphertext stealingCurrent tweak TF7D73FDACC0B64382D81CF8EDC9C338ANext tweak αT69AF7FB49917C8705A029F1DB9396714Short input1122334455Intermediate CC96ABE5533D250B0907AFBB84288AE963Tail + un-stolen bytes1122334455250B0907AFBB84288AE963Full output219BF750510C5D9F0DE3A9630D29B7FCStolen short output (5 bytes)96ABE5533DSector 7 · length 21 bytes · storage confidentiality only

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": "219BF750510C5D9F0DE3A9630D29B7FC96ABE5533D",
  "recovered": "00112233445566778899AABBCCDDEEFF1122334455",
  "length": 21
}
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

XTS uses two distinct AES keys: \(T_{0}\)=E(\(K_{2}\), sector encoded little-endian); \(T_{j+1}\)=α\(T_{j}\) in \(\mathrm{GF}(2^{128})\). C=E(\(K_{1}\),P XOR T) XOR T. If final block is short, ciphertext stealing preserves length. XTS is storage confidentiality, not authentication.

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

Draw the XTS data-key and tweak-key operations for a sector with one full block and a partial second block. Label the initial tweak, next tweak and ciphertext-stealing rearrangement. Explain why XTS does not authenticate storage.

02 · Storage reasoning

Storage reasoning · Independent work

For XTS data unit of 31 bytes, specify the last full block and partial length. Does ciphertext stealing increase ciphertext length? Why reject units shorter than one full block in ordinary XTS?

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

For the separate teaching-test configuration plaintext: 00112233445566778899AABBCCDDEEFF1122334455; key: 000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F; sector: 8, 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 · CR27-02

A teaching trace for XTS-AES · sector tweaks and ciphertext stealing contains step: Decrypt Ciphertext stealing; tweak: F7D73FDACC0B64382D81CF8EDC9C338A; next_tweak: 69AF7FB49917C8705A029F1DB9396714; full: 00112233445566778899AABBCCDDEEFF; partial: 1122334455. Explain the role of partial (recorded value 1122334455) 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 · CR27-03

The first teaching trace contains step: Ciphertext stealing; tweak: F7D73FDACC0B64382D81CF8EDC9C338A; next_tweak: 69AF7FB49917C8705A029F1DB9396714; full: 219BF750510C5D9F0DE3A9630D29B7FC; partial: 96ABE5533D; the last contains step: Decrypt Ciphertext stealing; tweak: F7D73FDACC0B64382D81CF8EDC9C338A; next_tweak: 69AF7FB49917C8705A029F1DB9396714; full: 00112233445566778899AABBCCDDEEFF; partial: 1122334455. 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 · CR27-04

Plan a comparison of plaintext: 00112233445566778899AABBCCDDEEFF1122334455; key: 000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F; sector: 7 with plaintext: 00112233445566778899AABBCCDDEEFF1122334455; key: 000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F; sector: 8. Record the dependent value recovered, 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 XTS tweaks and ciphertext stealing

  1. Write a prediction using the worked calculation in Concepts.
  2. Select Ciphertext stealing. Inspect current and next tweaks, intermediate CC, short input, combined block and both outputs. Select inverse and verify all 21 bytes.
  3. Export the trace and compare against the reference after recording your prediction.

Experimental inputs

Experimental reference · json
{"plaintext":"00112233445566778899AABBCCDDEEFF1122334455","key":"000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F","sector":"7"}
Verified baseline reference (check after predicting)
Experimental reference · json
{"ciphertext":"219BF750510C5D9F0DE3A9630D29B7FC96ABE5533D","recovered":"00112233445566778899AABBCCDDEEFF1122334455","length":21}

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

Sector, initial and next tweaks, intermediate stolen bytes, full and short output lengths and recovery.

Run baseline →
02

Part D · Controlled experiment — Trace XTS tweaks and ciphertext stealing

  1. Change sector to 8; restore 7 and append 11 zero bytes to make exactly 32 bytes. Compare first tweak, presence of ciphertext stealing, output length and recovery.
  2. Record all fixed settings and complete the trial table.
  3. Measure Sector, initial and next tweaks, intermediate stolen bytes, full and short output lengths and recovery. Compare against the baseline and explain the mechanism.
TrialInput configurationPredictionObservedVerification
1{"plaintext":"00112233445566778899AABBCCDDEEFF1122334455","key":"000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F","sector":"7"}
2{"plaintext":"00112233445566778899AABBCCDDEEFF1122334455","key":"000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F","sector":"8"}
3{"plaintext":"00112233445566778899AABBCCDDEEFF11223344550000000000000000000000","key":"000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F","sector":"7"}

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 sector 7 to 8, then append bytes to make two full blocks. First verified alternate: {"sector": "8"}.
  3. Keep both keys and unchanged bytes.
  4. Measure tweak, full and partial blocks, output length and recovery.
  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 CR27
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 CR27/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": "Ciphertext stealing",
    "tweak": "F7D73FDACC0B64382D81CF8EDC9C338A",
    "next_tweak": "69AF7FB49917C8705A029F1DB9396714",
    "full": "219BF750510C5D9F0DE3A9630D29B7FC",
    "partial": "96ABE5533D"
  },
  "result": {
    "ciphertext": "219BF750510C5D9F0DE3A9630D29B7FC96ABE5533D",
    "recovered": "00112233445566778899AABBCCDDEEFF1122334455",
    "length": 21
  }
}

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

# Generate sector tweaks and handle short final blocks using ciphertext stealing.
def xts(data,key,sector,dec=False):
    if len(data)<16 or len(key) not in (32,64): raise ValueError('XTS needs >=16 data bytes and 32 or 64 key bytes')
    k1,k2=key[:len(key)//2],key[len(key)//2:]
    if k1==k2: raise ValueError('Use distinct XTS keys')
    t=aes(sector.to_bytes(16,'little'),k2)[0]; out=b''; trace=[]
    def mulx(t):
        n=int.from_bytes(t,'little'); return (((n<<1)&((1<<128)-1))^(0x87 if n>>127 else 0)).to_bytes(16,'little')
    def xex(b,t,d): return xor(aes(xor(b,t),k1,d)[0],t)
    n,r=divmod(len(data),16)
    for i in range(n-(1 if r else 0)):
        b=data[16*i:16*i+16]; c=xex(b,t,dec); trace.append(row(f'Block {i}',tweak=hexs(t),input=hexs(b),output=hexs(c))); out+=c; t=mulx(t)
    if r:
        b=data[16*(n-1):16*n]; tail=data[16*n:]; tn=mulx(t)
        if not dec:
            cc=xex(b,t,False); partial=cc[:r]; full=xex(tail+cc[r:],tn,False)
        else:
            pp=xex(b,tn,True); partial=pp[:r]; full=xex(tail+pp[r:],t,True)
        out+=full+partial; trace.append(row('Ciphertext stealing',tweak=hexs(t),next_tweak=hexs(tn),full=hexs(full),partial=hexs(partial)))
    return out,trace

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

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

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

EXTRA = {}

def run(p):
    s=b(p['plaintext']);k=b(p['key']);sector=n(p['sector'])
    if not 0<=sector<=9007199254740991: raise ValueError('Sector must be a nonnegative safe integer')
    c,t=xts(s,k,sector);d,u=xts(c,k,sector,True);return pack({'ciphertext':hexs(c),'recovered':hexs(d),'length':len(c)},t+[dict(x,step='Decrypt '+x['step']) for x in u])

PARAMS = {'plaintext': '00112233445566778899AABBCCDDEEFF1122334455', 'key': '000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F', 'sector': '7'}
EXPECTED = {'ciphertext': '219BF750510C5D9F0DE3A9630D29B7FC96ABE5533D', 'recovered': '00112233445566778899AABBCCDDEEFF1122334455', 'length': 21}
ALT = {'plaintext': '00112233445566778899AABBCCDDEEFF1122334455', 'key': '000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F', 'sector': '8'}
ALT_EXPECTED = {'ciphertext': 'F2FE3C63A973D11C41DC328B0C3AACB95082C174BB', 'recovered': '00112233445566778899AABBCCDDEEFF1122334455', 'length': 21}

if __name__ == "__main__":
    import argparse, json
    parser=argparse.ArgumentParser(description="CR27 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("CR27 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": "219BF750510C5D9F0DE3A9630D29B7FC96ABE5533D",
  "recovered": "00112233445566778899AABBCCDDEEFF1122334455",
  "length": 21
}

05 · Interactive flashcards

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

Browse all explanations
Why does an identical block at two sector positions differ?

Different tweaks alter the block transformation.

What is the dependent variable in this lab?

tweak, full and partial blocks, output length and recovery

What must remain controlled?

both keys and unchanged bytes

What input settings define the baseline for this experiment?

plaintext = 00112233445566778899AABBCCDDEEFF1122334455; key = 000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F; sector = 7

What is the first intermediate state in the baseline?

step: Ciphertext stealing; tweak: F7D73FDACC0B64382D81CF8EDC9C338A; next_tweak: 69AF7FB49917C8705A029F1DB9396714; full: 219BF750510C5D9F0DE3A9630D29B7FC; partial: 96ABE5533D

What generates T₀?

AES under the independent tweak key \(K_{2}\).

What does α multiplication do?

Produces the next block tweak in \(\mathrm{GF}(2^{128})\).

Does XTS authenticate storage?

No; integrity requires a separate appropriate mechanism.

06 · Knowledge assessment

Formative check

Why is ciphertext stealing used in XTS?

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

Independent assessment

Use 31 bytes of data under two distinct sectors, compare output lengths and identify full versus stolen ciphertext bytes. Verify that decrypting under the wrong sector does not recover the plaintext. 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 · CR28 →

How to investigate · CR27

Independent variable: sector 7 to 8, then append bytes to make two full blocks.

Controlled variables: both keys and unchanged bytes.

Dependent evidence: tweak, full and partial blocks, output length and recovery.

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

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