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 · CR34 · RANDOMNESS
IoT Security and Privacy

Entropy · bias, conditioning and OS randomness

A physical entropy source (e.g.

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

Scope and objectives

Scope of the experiment

Physical entropy sources depend on nondeterministic physical processes; a deterministic simulation only models their output. Conditioning can reduce certain biases but cannot manufacture entropy from deterministic input.

The focus of this experiment is to measure bit bias and entropy in a finite sample. Students then trace Von Neumann pair acceptance and discarded pairs, and distinguish conditioning assumptions from OS-generated cryptographic randomness. 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

  • Measure bit bias and entropy in a finite sample.
  • Trace Von Neumann pair acceptance and discarded pairs.
  • Distinguish conditioning assumptions from OS-generated cryptographic randomness.
  • 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 measure bit bias and entropy in a finite sample, trace Von Neumann pair acceptance and discarded pairs, and distinguish conditioning assumptions from OS-generated cryptographic randomness.

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 distinguish conditioning assumptions from OS-generated cryptographic randomness. 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 RC4 · KSA and PRGA state array.

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

CR34 · Entropy · bias, conditioning and OS randomness

Von Neumann conditioning consumes nonoverlapping pairs: equal bits 00/11 are discarded; 01 maps to 0 and 10 maps to 1. Under independent identically distributed biased input the accepted bits are unbiased; correlated input can violate this assumption. An odd trailing bit is not processed. Empirical entropy is not a source assessment. OS randomness is obtained from the operating system, not from this synthetic sequence.

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

Von Neumann conditioning consumes nonoverlapping pairs: equal bits 00/11 are discarded; 01 maps to 0 and 10 maps to 1. Under independent identically distributed biased input the accepted bits are unbiased; correlated input can violate this assumption. An odd trailing bit is not processed. Empirical entropy is not a source assessment. OS randomness is obtained from the operating system, not from this synthetic sequence.

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.

Entropy sources and conditioning

1 · Principles and purpose

Physical entropy sources depend on nondeterministic physical processes; a deterministic simulation only models their output. Conditioning can reduce certain biases but cannot manufacture entropy from deterministic input.

2 · Mathematical and algorithmic foundations

Von Neumann pairing discards 00 and 11 and maps 01→0,10→1. Under independent identically biased input bits, P(01)=P(10)=p(1−p). Correlation invalidates the simple argument.

3 · Worked teaching example

Pairs 01,00,10,11 yield 0,discard,1,discard. Retention is 2/4 pairs, not a proof of unpredictability. OS randomness abstracts collection and conditioning.

Verified default trace · 16 intermediate states

Given parameters (teaching example):

{
  "bits": "00010001100000110000100100100001"
}
StageComputed values
1{ "step": "Pair 1", "input": "00", "output": "discard" }
2{ "step": "Pair 2", "input": "01", "output": 0 }
3{ "step": "Pair 3", "input": "00", "output": "discard" }
4{ "step": "Pair 4", "input": "01", "output": 0 }
5{ "step": "Pair 5", "input": "10", "output": 1 }
6{ "step": "Pair 6", "input": "00", "output": "discard" }
7{ "step": "Pair 7", "input": "00", "output": "discard" }
8{ "step": "Pair 8", "input": "11", "output": "discard" }
9{ "step": "Pair 9", "input": "00", "output": "discard" }
10{ "step": "Pair 10", "input": "00", "output": "discard" }
11{ "step": "Pair 11", "input": "10", "output": 1 }
12{ "step": "Pair 12", "input": "01", "output": 0 }
13{ "step": "Pair 13", "input": "00", "output": "discard" }
14{ "step": "Pair 14", "input": "10", "output": 1 }
15{ "step": "Pair 15", "input": "00", "output": "discard" }
16{ "step": "Pair 16", "input": "01", "output": 0 }

Recorded result

{
  "output": "0011010",
  "input_n": 32,
  "output_n": 7,
  "discarded_pairs": 9,
  "input_entropy": 0.857148,
  "output_entropy": 0.985228
}

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

Empirical binary entropy

p is the observed fraction of one bits, with 0 log 0 defined as zero. This measures marginal distribution, not sequence unpredictability or cryptographic strength.

\[H_2(p)=-p\log_2p-(1-p)\log_2(1-p)\]

For p=0.5 the result is one bit; for p=1 it is zero.

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.

Entropy · bias, conditioning and OS randomness: independent state notebook135710121416Pair 1input00outputdiscard

Step 1 of 8 · Pair 1

Pair 1

step
Pair 1
input
00
output
discard

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.
Von Neumann conditioning · Pair 2Input pair01Equal bits?NOOutput00011010Output 7 / 32 bits · discarded pairs 9 · no physical entropy measured

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

{
  "output": "0011010",
  "input_n": 32,
  "output_n": 7,
  "discarded_pairs": 9,
  "input_entropy": 0.857148,
  "output_entropy": 0.985228
}
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

A physical entropy source (e.g. thermal noise) needs health testing and optional conditioning; a DRBG expands entropy deterministically. Simulated biased input is not physical noise. Pairwise Von Neumann conditioning maps 01→0,10→1, discards equal pairs; independence assumption matters. Intel architecture separates noise, conditioning and deterministic output. Python secrets uses OS randomness, not direct hardware measurement.

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

Apply the Von Neumann pair rule to 001001110110. Tabulate each nonoverlapping pair, whether it is retained and the extracted bit. Explain the assumptions and why a simulation is not physical entropy.

02 · Conditioning

Conditioning · Independent work

Apply 01→0,10→1, discard equal to bits 0110001110. Count kept and discarded pairs.

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

For the separate teaching-test configuration bits: 0101010101010101, predict input_n 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 · CR34-02

A teaching trace for Entropy · bias, conditioning and OS randomness contains step: Pair 2; input: 01; output: 0. Explain the role of output (recorded value 0) 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 · CR34-03

The first teaching trace contains step: Pair 1; input: 00; output: discard; the last contains step: Pair 16; input: 01; output: 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 · CR34-04

Plan a comparison of bits: 00010001100000110000100100100001 with bits: 0101010101010101. 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

Measure pair conditioning and its limitations

  1. Write a prediction using the worked calculation in Concepts.
  2. Trace the baseline pairs and record each accepted or discarded output. Compute acceptance ratio as output_n divided by number of complete input pairs.
  3. Export the trace and compare against the reference after recording your prediction.

Experimental inputs

Experimental reference · json
{"bits":"00010001100000110000100100100001"}
Verified baseline reference (check after predicting)
Experimental reference · json
{"output":"0011010","input_n":32,"output_n":7,"discarded_pairs":9,"input_entropy":0.857148,"output_entropy":0.985228}

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

Input length, complete pairs, accepted output, discarded pairs, acceptance ratio, input/output empirical entropy; explicitly distinguish no output from zero entropy.

Run baseline →
02

Part D · Controlled experiment — Measure pair conditioning and its limitations

  1. Use 0101010101010101, then 0000000000000000, then 00011011. Predict the output and compare acceptance and empirical entropy. Keep the mapping rule fixed.
  2. Record all fixed settings and complete the trial table.
  3. Measure Input length, complete pairs, accepted output, discarded pairs, acceptance ratio, input/output empirical entropy; explicitly distinguish no output from zero entropy. Compare against the baseline and explain the mechanism.
TrialInput configurationPredictionObservedVerification
1{"bits":"00010001100000110000100100100001"}
2{"bits":"0101010101010101"}
3{"bits":"0000000000000000"}
4{"bits":"00011011"}

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 bits to 0101010101010101 and then a long biased sequence. First verified alternate: {"bits": "0101010101010101"}.
  3. Keep conditioning rule.
  4. Measure input/output count, discarded pairs and empirical entropy.
  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 CR34
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 CR34/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": "Pair 1",
    "input": "00",
    "output": "discard"
  },
  "result": {
    "output": "0011010",
    "input_n": 32,
    "output_n": 7,
    "discarded_pairs": 9,
    "input_entropy": 0.857148,
    "output_entropy": 0.985228
  }
}

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
# ============================================================
# CR34 | Educational implementation and trace functions
# Copyright © 2026/2027 Dr. Mohammad Alja’afreh
# PSUT IoT Engineering Studio | Educational, synthetic inputs
# ============================================================
import math

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

# Summarize marginal bit frequencies and simple dependence, not cryptographic strength.
def metrics(bits):
    n=len(bits); p=sum(bits)/n; entropy=-sum(x*math.log2(x) for x in (p,1-p) if x); runs=1+sum(a!=b for a,b in zip(bits,bits[1:])); match=sum(a==b for a,b in zip(bits,bits[1:]))/(n-1) if n>1 else 0
    return {'ones':sum(bits),'n':n,'fraction':round(p,6),'runs':runs,'entropy':round(entropy,6),'adjacent_match':round(match,6)}

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

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

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

def bitseq(s):
    if not s or len(s)>4096 or set(s)-{'0','1'}: raise ValueError('Enter 1–4096 binary digits')
    return [int(v) for v in s]

EXTRA = {}

def run(p):
    s=bitseq(p['bits']);out=[];t=[]
    if len(s)<2: raise ValueError('Enter at least one complete bit pair')
    for i in range(0,len(s)-1,2):
        a,b0=s[i:i+2];v=a if a!=b0 else None
        if v is not None:out.append(v)
        t.append(row(f'Pair {i//2+1}',input=f'{a}{b0}',output=v if v is not None else 'discard'))
    return pack({'output':''.join(map(str,out)),'input_n':len(s),'output_n':len(out),'discarded_pairs':len(s)//2-len(out),'input_entropy':metrics(s)['entropy'],'output_entropy':metrics(out)['entropy'] if out else None},t)

PARAMS = {'bits': '00010001100000110000100100100001'}
EXPECTED = {'output': '0011010', 'input_n': 32, 'output_n': 7, 'discarded_pairs': 9, 'input_entropy': 0.857148, 'output_entropy': 0.985228}
ALT = {'bits': '0101010101010101'}
ALT_EXPECTED = {'output': '00000000', 'input_n': 16, 'output_n': 8, 'discarded_pairs': 0, 'input_entropy': 1.0, 'output_entropy': -0.0}

if __name__ == "__main__":
    import argparse, json
    parser=argparse.ArgumentParser(description="CR34 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("CR34 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": "0011010",
  "input_n": 32,
  "output_n": 7,
  "discarded_pairs": 9,
  "input_entropy": 0.857148,
  "output_entropy": 0.985228
}

05 · Interactive flashcards

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

Browse all explanations
Does hashing or conditioning create physical entropy?

No; it can concentrate existing entropy but cannot create new uncertainty.

What is the dependent variable in this lab?

input/output count, discarded pairs and empirical entropy

What must remain controlled?

conditioning rule

What input settings define the baseline for this experiment?

bits = 00010001100000110000100100100001

What is the first intermediate state in the baseline?

step: Pair 1; input: 00; output: discard

What happens to equal pairs?

They are discarded.

What happens to an unpaired final bit?

It is not processed.

Does software simulation measure physical entropy?

No.

06 · Knowledge assessment

Formative check

Under which condition is the pair method unbiased?

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

Independent assessment

Compare 0011001100110011 and 0101010101010101 as simulated raw input. Count discarded pairs, output bits and empirical entropy; explain why the independence assumption and OS entropy provenance matter. 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 · CR35 →

How to investigate · CR34

Independent variable: bits to 0101010101010101 and then a long biased sequence.

Controlled variables: conditioning rule.

Dependent evidence: input/output count, discarded pairs and empirical entropy.

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

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