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 · CR01 · FEISTEL
IoT Security and Privacy

Feistel · two-round worked example

Split a 32-bit word into 16-bit halves.

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

Scope and objectives

Scope of the experiment

Confusion obscures the relation between key and ciphertext; diffusion spreads a change across many output positions. Substitution changes symbols, whereas permutation rearranges positions. A Feistel network alternates mixing with exchange; it does not require an invertible round function.

The focus of this experiment is to derive forward and inverse Feistel rounds using XOR cancellation. Students then trace half-block rotation, key mixing and final swap, and verify hexadecimal recovery with reversed round keys. 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

  • Derive forward and inverse Feistel rounds using XOR cancellation.
  • Trace half-block rotation, key mixing and final swap.
  • Verify hexadecimal recovery with reversed round keys.
  • 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 derive forward and inverse Feistel rounds using XOR cancellation, trace half-block rotation, key mixing and final swap, and verify hexadecimal recovery with reversed round keys.

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 hexadecimal recovery with reversed round keys. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the foundational terminology in Concepts and confirm readiness using the existing setup instructions. After completion, continue to Feistel · round design and diffusion.

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

CR01 · Feistel · two-round worked example

Split a 32-bit word into 16-bit halves. \(L_{i+1}\)=\(R_{i}\); \(R_{i+1}\)=\(L_{i}\) XOR F(\(R_{i}\),\(K_{i}\)). F is K XOR ROTL16(R,4). Rotation wraps discarded bits; XOR is carry-free. Swap final halves to encrypt; reverse keys to decrypt. The final swap and reverse-key recovery verify the calculation.

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

Split a 32-bit word into 16-bit halves. \(L_{i+1}\)=\(R_{i}\); \(R_{i+1}\)=\(L_{i}\) XOR F(\(R_{i}\),\(K_{i}\)). F is K XOR ROTL16(R,4). Rotation wraps discarded bits; XOR is carry-free. Swap final halves to encrypt; reverse keys to decrypt. The final swap and reverse-key recovery verify the calculation.

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.

Product cipher and reversibility

1 · Principles and purpose

Confusion obscures the relation between key and ciphertext; diffusion spreads a change across many output positions. Substitution changes symbols, whereas permutation rearranges positions. A Feistel network alternates mixing with exchange; it does not require an invertible round function.

2 · Mathematical and algorithmic foundations

\(L^{\prime}=R,\quad R^{\prime}=L\oplus F(R,K)\). Recover R=L′ and L=R′⊕F(L′,K), because \(x\oplus y\oplus y=x\). ROTL16(R,4)=((R<<4)|(R>>12)) & 0xFFFF. F=K⊕ROTL16(R,4). The inverse follows from copying R and XOR cancellation, not from inverting F. Final swapping permits the same structure with reversed keys.

\[\begin{aligned}L_{i+1}&=R_i\\ R_{i+1}&=L_i\oplus F(R_i,K_i)\\ F(R_i,K_i)&=K_i\oplus\operatorname{ROTL}_{16}(R_i,4)\\ R_i&=L_{i+1},\quad L_i=R_{i+1}\oplus F(L_{i+1},K_i)\end{aligned}\]

3 · Worked teaching example

For R=BF0D, the rotation is F0DB. With K=1010, F=E0CB; FACC⊕E0CB=1A07. Next use R=1A07: rotation A071, F=0B5E, BF0D⊕0B5E=B453. Swap to B4531A07. A linear toy F is not a secure design.

Verified default trace · 5 intermediate states

Given parameters (teaching example):

{
  "plaintext": "FACCBF0D",
  "keys": "1010,AB2F",
  "rotation": "4"
}
StageComputed values
1{ "step": "Split", "L": "FACC", "R": "BF0D" }
2{ "step": "Round 0", "key": "1010", "rotated": "F0DB", "F": "E0CB", "L": "BF0D", "R": "1A07", "xor": "FACC XOR E0CB" }
3{ "step": "Round 1", "key": "AB2F", "rotated": "A071", "F": "0B5E", "L": "1A07", "R": "B453", "xor": "BF0D XOR 0B5E" }
4{ "step": "Final swap", "ciphertext": "B4531A07" }
5{ "step": "Reverse keys", "recovered": "FACCBF0D" }

Recorded result

{
  "ciphertext": "B4531A07",
  "recovered": "FACCBF0D"
}

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

Feistel round and inverse

L and R denote equal-width half-blocks; K is the round key. XOR is its own inverse, so recovering the old halves does not require inverting the round function F.

\[\begin{aligned}L_{i+1}&=R_i, &R_{i+1}&=L_i\oplus F(R_i,K_i)\\R_i&=L_{i+1}, &L_i&=R_{i+1}\oplus F(L_{i+1},K_i)\end{aligned}\]

If the same 16-bit round-function output is XORed twice into a half-block, the original half-block is recovered.

Concept animation · Feistel round data flow

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.

Feistel · two-round worked example: Feistel round data flow32-bit plaintextFACCBF0DLeft 16 bitsFACCRight 16 bitsBF0D

Step 1 of 5 · Split plaintext

Split plaintext

step
Split
L
FACC
R
BF0D

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.
CR01 calculated stateFeistel round · data movementInput LFACCInput RBF0DROTL(R)F0DBRound key1010F = key XOR rotationE0CBNew R = old L XOR F1A07New L = old RBF0DThe swap copies R; XOR is reversible.

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.

Calculated result

{
  "ciphertext": "B4531A07",
  "recovered": "FACCBF0D"
}
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

Split a 32-bit word into 16-bit halves. \(L_{i+1}\)=\(R_{i}\); \(R_{i+1}\)=\(L_{i}\) XOR F(\(R_{i}\),\(K_{i}\)). F is K XOR ROTL16(R,4). Rotation wraps discarded bits; XOR is carry-free. Swap final halves to encrypt; reverse keys to decrypt. The final swap and reverse-key recovery verify the calculation.

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

For plaintext 12345678 (hex) and keys 1010, AB2F, compute two rounds with rotation 4. Tabulate L, R, rotated R, F and XOR at each round. Swap the final halves and demonstrate the inverse using the reversed key order.

02 · Algorithm tracing

Algorithm tracing · Independent work

For one 16-bit-half Feistel round L=0001,R=1000,K=0010, rotation4, calculate output and invert it without inverting F.

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

For the separate teaching-test configuration plaintext: FACCBF0D; keys: 1010,AB2F; rotation: 1, predict recovered 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 · CR01-02

A teaching trace for Feistel · two-round worked example contains step: Round 0; key: 1010; rotated: F0DB; F: E0CB; L: BF0D. Explain the role of xor (recorded value FACC XOR E0CB) 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 · CR01-03

The first teaching trace contains step: Split; L: FACC; R: BF0D; the last contains step: Reverse keys; recovered: FACCBF0D. 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 · CR01-04

Plan a comparison of plaintext: FACCBF0D; keys: 1010,AB2F; rotation: 4 with plaintext: FACCBF0D; keys: 1010,AB2F; rotation: 1. 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 both Feistel rounds by hand

  1. Use the exact baseline input below and write a prediction.
  2. Write L0=FACC and R0=BF0D. Rotate R0 left by four bits, XOR with 1010, then XOR with L0. Repeat with AB2F. Swap final halves and reverse the key order.
  3. Save the trace and compare it with the reference output.

Experimental inputs

Experimental reference · json
{"plaintext":"FACCBF0D","keys":"1010,AB2F","rotation":"4"}
Verified baseline reference (check after predicting)
Experimental reference · json
{"ciphertext":"B4531A07","recovered":"FACCBF0D"}

Default ciphertext B4531A07; recovered FACCBF0D. Verify reverse-key recovery in each trial.

Evidence to record

L, R, rotation, F, XOR, ciphertext and recovered plaintext for every round.

Run baseline →
02

Part D · Controlled investigation

  1. Set rotation to 0, then 1; use the same block and both keys. Add a separate three-round run using keys 1010,AB2F,4321.
  2. Record the conditions held fixed: plaintext and both keys
  3. Collect L, R, rotation, F, XOR, ciphertext and recovered plaintext for every round. Compare the first differing intermediate step and explain the relationship.
TrialInput configurationPredictionObservedVerification
1{"plaintext":"FACCBF0D","keys":"1010,AB2F","rotation":"4"}
2{"plaintext":"FACCBF0D","keys":"1010,AB2F","rotation":"1"}

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 at least one changed input; compare the intermediate values with the browser where supported.
  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 rotation from 4 to 0 and then 1. First verified alternate: {"rotation": "1"}.
  3. Keep plaintext and both keys.
  4. Measure L,R, rotated R, F and recovered plaintext.
  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 CR01
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 CR01/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": "Split",
    "L": "FACC",
    "R": "BF0D"
  },
  "result": {
    "ciphertext": "B4531A07",
    "recovered": "FACCBF0D"
  }
}

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
# ============================================================
# CR01 | 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}'

# 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 row(label,**values): return {'step':label,**values}

# Trace left/right halves, rotation and XOR; final swap makes reverse-key decryption possible.
def feistel(p,keys,w=16,shift=4):
    mask=(1<<w)-1; L,R=p>>w,p&mask; trace=[row('Split',L=hx(L,w//4),R=hx(R,w//4))]
    for i,k in enumerate(keys):
        z=rot(R,shift%w,w); f=k^z; old=L; L,R=R,L^f
        trace.append(row(f'Round {i}',key=hx(k,w//4),rotated=hx(z,w//4),F=hx(f,w//4),L=hx(L,w//4),R=hx(R,w//4),xor=f'{hx(old,w//4)} XOR {hx(f,w//4)}'))
    return (R<<w)|L,trace

# 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))

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

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

EXTRA = {}

def run(p):
    p0=int(p['plaintext'],16); keys=[int(x,16) for x in p['keys'].split(',')]; k=n(p['rotation'])
    if not 0<=p0<2**32 or not 1<=len(keys)<=16 or any(not 0<=x<65536 for x in keys) or not 0<=k<16: raise ValueError('32-bit block, 1–16 16-bit keys, rotation 0–15')
    c,t=feistel(p0,keys,shift=k); recovered,_=feistel(c,keys[::-1],shift=k)
    return pack({'ciphertext':hx(c,8),'recovered':hx(recovered,8)},t+[row('Final swap',ciphertext=hx(c,8)),row('Reverse keys',recovered=hx(recovered,8))])

PARAMS = {'plaintext': 'FACCBF0D', 'keys': '1010,AB2F', 'rotation': '4'}
EXPECTED = {'ciphertext': 'B4531A07', 'recovered': 'FACCBF0D'}
ALT = {'plaintext': 'FACCBF0D', 'keys': '1010,AB2F', 'rotation': '1'}
ALT_EXPECTED = {'ciphertext': '3DAD94C7', 'recovered': 'FACCBF0D'}

if __name__ == "__main__":
    import argparse, json
    parser=argparse.ArgumentParser(description="CR01 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("CR01 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": "B4531A07",
  "recovered": "FACCBF0D"
}

05 · Interactive flashcards

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

Browse all explanations
Why does decryption not require inverting F?

The original right half is copied to L; XOR reverses mixing when the key order is reversed.

What is the dependent variable in this lab?

L,R, rotated R, F and recovered plaintext

What must remain controlled?

plaintext and both keys

What input settings define the baseline for this experiment?

plaintext = FACCBF0D; keys = 1010,AB2F; rotation = 4

What is the first intermediate state in the baseline?

step: Split; L: FACC; R: BF0D

What check must you reproduce before varying the inputs?

Default ciphertext B4531A07; recovered FACCBF0D. Verify reverse-key recovery in each trial.

Which observations belong in your experimental record?

L, R, rotation, F, XOR, ciphertext and recovered plaintext for every round.

06 · Knowledge assessment

Formative check

Which experimental design best isolates the effect of the specified input?

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

Independent assessment

Using the two provided keys, choose a new 32-bit plaintext. Derive both rounds on paper, including rotation and XOR; use the trace to locate any arithmetic discrepancy. Prove the reverse-key roundtrip. 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 · CR02 →

How to investigate · CR01

Independent variable: rotation from 4 to 0 and then 1.

Controlled variables: plaintext and both keys.

Dependent evidence: L,R, rotated R, F and recovered plaintext.

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

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