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

Blum Blum Shub · modular squaring

Select distinct primes p,q≡3 mod 4, n=pq; choose coprime seed s and initialize \(x_{0}\)=\(s^{2}\) mod n.

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

Scope and objectives

Scope of the experiment

BBS uses modular squaring with a modulus formed from distinct primes congruent to 3 modulo 4. The seed must be coprime to the modulus; classroom parameters are intentionally small.

The focus of this experiment is to trace Blum Blum Shub modular squaring with valid classroom primes. Students then calculate extracted bits and check the seed coprimality condition, and explain the distinction between toy parameters and security assumptions. 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 Blum Blum Shub modular squaring with valid classroom primes.
  • Calculate extracted bits and check the seed coprimality condition.
  • Explain the distinction between toy parameters and security assumptions.
  • 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 Blum Blum Shub modular squaring with valid classroom primes, calculate extracted bits and check the seed coprimality condition, and explain the distinction between toy parameters and security assumptions.

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 explain the distinction between toy parameters and security assumptions. 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-OFB and CTR · deterministic bit generation.

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

CR31 · Blum Blum Shub · modular squaring

BBS selects distinct primes p,q congruent to 3 modulo 4, a seed coprime to n=pq, and initializes \(x_{0}\)=\(s^{2}\) mod n. Each iteration squares the current state modulo n and outputs its least significant bit. Small public classroom parameters provide no real security.

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

BBS selects distinct primes p,q congruent to 3 modulo 4, a seed coprime to n=pq, and initializes \(x_{0}\)=\(s^{2}\) mod n. Each iteration squares the current state modulo n and outputs its least significant bit. Small public classroom parameters provide no real security.

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.

Blum Blum Shub

1 · Principles and purpose

BBS uses modular squaring with a modulus formed from distinct primes congruent to 3 modulo 4. The seed must be coprime to the modulus; classroom parameters are intentionally small.

2 · Mathematical and algorithmic foundations

n=pq; x0=\(s^{2}\) mod n; \(x_{i+1}\)=\(x_{i}^{2}\) mod n. A simple output rule is the least significant bit. Keep internal state distinct from returned bits.

\[n=pq,\quad x_0=s^2\bmod n,\quad x_{i+1}=x_i^2\bmod n,\quad b_i=x_i\bmod2\]

3 · Worked teaching example

With p=7,q=11,s=2, n=77,x0=4,x1=16,x2=25,x3=9. Output bits are 0,1,1. Tiny examples do not provide production security.

Verified default trace · 16 intermediate states

Given parameters (teaching example):

{
  "seed": "5",
  "p": "7",
  "q": "11",
  "count": "16"
}
StageComputed values
1{ "step": "Step 1", "previous": 25, "state": 9, "bit": 1 }
2{ "step": "Step 2", "previous": 9, "state": 4, "bit": 0 }
3{ "step": "Step 3", "previous": 4, "state": 16, "bit": 0 }
4{ "step": "Step 4", "previous": 16, "state": 25, "bit": 1 }
5{ "step": "Step 5", "previous": 25, "state": 9, "bit": 1 }
6{ "step": "Step 6", "previous": 9, "state": 4, "bit": 0 }
7{ "step": "Step 7", "previous": 4, "state": 16, "bit": 0 }
8{ "step": "Step 8", "previous": 16, "state": 25, "bit": 1 }
9{ "step": "Step 9", "previous": 25, "state": 9, "bit": 1 }
10{ "step": "Step 10", "previous": 9, "state": 4, "bit": 0 }
11{ "step": "Step 11", "previous": 4, "state": 16, "bit": 0 }
12{ "step": "Step 12", "previous": 16, "state": 25, "bit": 1 }
13{ "step": "Step 13", "previous": 25, "state": 9, "bit": 1 }
14{ "step": "Step 14", "previous": 9, "state": 4, "bit": 0 }
15{ "step": "Step 15", "previous": 4, "state": 16, "bit": 0 }
16{ "step": "Step 16", "previous": 16, "state": 25, "bit": 1 }

Recorded result

{
  "bits": "1001100110011001",
  "ones": 8,
  "n": 16,
  "fraction": 0.5,
  "runs": 9,
  "entropy": 1.0,
  "adjacent_match": 0.466667
}

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

Blum Blum Shub recurrence

p and q are distinct primes congruent to 3 modulo 4, and seed s is coprime to n. The extracted least significant bit is not the entire state.

\[n=pq,\quad x_0=s^2\bmod n,\qquad x_{i+1}=x_i^2\bmod n,\quad b_i=x_{i+1}\bmod2\]

Concept animation · BBS modular state progression

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.

Initial state9x0—x1—x2—x3—x4—x5n = 7 × 11 = 77 · extract low bit after each updateSquaring step 19x04x1—x2—x3—x4—x5n = 7 × 11 = 77 · extract low bit after each updateSquaring step 29x04x116x2—x3—x4—x5n = 7 × 11 = 77 · extract low bit after each updateSquaring step 39x04x116x225x3—x4—x5n = 7 × 11 = 77 · extract low bit after each updateSquaring step 49x04x116x225x39x4—x5n = 7 × 11 = 77 · extract low bit after each updateSquaring step 59x04x116x225x39x44x5n = 7 × 11 = 77 · extract low bit after each update

Step 1 of 6 · Initial state

Initial state

x₀ = 3² mod 77 = 9.

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.
Blum Blum Shub · square and extract parityPrevious x25x²625mod 779LSB11001100110011001Initial x₀=s² mod n; these tiny parameters are instructional 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

{
  "bits": "1001100110011001",
  "ones": 8,
  "n": 16,
  "fraction": 0.5,
  "runs": 9,
  "entropy": 1.0,
  "adjacent_match": 0.466667
}
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

Select distinct primes p,q≡3 mod 4, n=pq; choose coprime seed s and initialize \(x_{0}\)=\(s^{2}\) mod n. \(x_{i+1}\)=\(x_{i}^{2}\) mod n, output least significant bit. Tiny public factors here are instructional, not secure.

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 p=7, q=11, modulus 77 and seed 3, calculate the initial squared state and the next six modular squarings; extract each least-significant bit. Check coprimality and explain why these small parameters are educational only.

02 · Recurrence

Recurrence · Independent work

For p=7,q=11 and coprime seed2, calculate x0 and next three squarings modulo77, with output LSBs of next three states.

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

For the separate teaching-test configuration seed: 9; p: 7; q: 11; count: 16, predict ones 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 · CR31-02

A teaching trace for Blum Blum Shub · modular squaring contains step: Step 2; previous: 9; state: 4; bit: 0. Explain the role of bit (recorded value 0) and identify the rule or input that determines it. Distinguish an intermediate state from the final result.

Intermediate · Compare two recorded states

Independent theoretical exercise · CR31-03

The first and final trace records show previous = 25 and 16. Calculate the signed difference and explain whether it is an operation count, a state value or a measurement.

Challenging · Controlled algorithm verification

Independent theoretical exercise · CR31-04

Plan a comparison of seed: 5; p: 7; q: 11; count: 16 with seed: 9; p: 7; q: 11; count: 16. Record the dependent value bits, 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

Follow modular squaring and parity extraction

  1. Write a prediction using the worked calculation in Concepts.
  2. Predict \(x_{1}\) and \(x_{2}\), inspect the stepwise squaring and verify extracted parity. Record the 16 generated bits and their empirical metrics.
  3. Export the trace and compare against the reference after recording your prediction.

Experimental inputs

Experimental reference · json
{"seed":"5","p":"7","q":"11","count":"16"}
Verified baseline reference (check after predicting)
Experimental reference · json
{"bits":"1001100110011001","ones":8,"n":16,"fraction":0.5,"runs":9,"entropy":1.0,"adjacent_match":0.466667}

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

n, \(x_{0}\), first four states, output sequence, ones fraction and runs.

Run baseline →
02

Part D · Controlled experiment — Follow modular squaring and parity extraction

  1. Change seed to 9; restore 5 and set p=11,q=19 together as one new modulus configuration. Keep count fixed. Compare states, bits and balance.
  2. Record all fixed settings and complete the trial table.
  3. Measure n, \(x_{0}\), first four states, output sequence, ones fraction and runs. Compare against the baseline and explain the mechanism.
TrialInput configurationPredictionObservedVerification
1{"seed":"5","p":"7","q":"11","count":"16"}
2{"seed":"9","p":"7","q":"11","count":"16"}
3{"seed":"5","p":"11","q":"19","count":"16"}

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 seed 5 to 9; then p,q to 11,19. First verified alternate: {"seed": "9"}.
  3. Keep count and other parameters.
  4. Measure internal state, output bits and observed balance.
  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 CR31
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 CR31/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": "Step 1",
    "previous": 25,
    "state": 9,
    "bit": 1
  },
  "result": {
    "bits": "1001100110011001",
    "ones": 8,
    "n": 16,
    "fraction": 0.5,
    "runs": 9,
    "entropy": 1.0,
    "adjacent_match": 0.466667
  }
}

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
# ============================================================
# CR31 | 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}

# Square the state modulo p*q and extract its low bit; small parameters are for teaching.
def bbs(seed,p,q,n):
    prime=lambda x: x>1 and all(x%i for i in range(2,math.isqrt(x)+1))
    if p==q or p%4!=3 or q%4!=3 or not prime(p) or not prime(q) or not 1<seed<p*q or math.gcd(seed,p*q)!=1: raise ValueError('Distinct small primes 3 mod 4 and coprime seed required')
    m=p*q; x=seed*seed%m; trace=[]; bits=[]
    for i in range(n):
        old=x; x=x*x%m; bits.append(x&1); trace.append(row(f'Step {i+1}',previous=old,state=x,bit=x&1))
    return bits,trace

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

EXTRA = {}

def run(p):
    count=n(p['count'])
    if not 1<=count<=256 or n(p['p'])*n(p['q'])>1000000: raise ValueError('Count 1–256; small primes only')
    s,t=bbs(n(p['seed']),n(p['p']),n(p['q']),count);return pack({'bits':''.join(map(str,s)),**metrics(s)},t)

PARAMS = {'seed': '5', 'p': '7', 'q': '11', 'count': '16'}
EXPECTED = {'bits': '1001100110011001', 'ones': 8, 'n': 16, 'fraction': 0.5, 'runs': 9, 'entropy': 1.0, 'adjacent_match': 0.466667}
ALT = {'seed': '9', 'p': '7', 'q': '11', 'count': '16'}
ALT_EXPECTED = {'bits': '0110011001100110', 'ones': 8, 'n': 16, 'fraction': 0.5, 'runs': 9, 'entropy': 1.0, 'adjacent_match': 0.466667}

if __name__ == "__main__":
    import argparse, json
    parser=argparse.ArgumentParser(description="CR31 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("CR31 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
{
  "bits": "1001100110011001",
  "ones": 8,
  "n": 16,
  "fraction": 0.5,
  "runs": 9,
  "entropy": 1.0,
  "adjacent_match": 0.466667
}

05 · Interactive flashcards

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

Browse all explanations
Why are these tiny primes unsafe?

Their product is trivially factorable; real security needs much larger appropriate parameters.

What is the dependent variable in this lab?

internal state, output bits and observed balance

What must remain controlled?

count and other parameters

What input settings define the baseline for this experiment?

seed = 5; p = 7; q = 11; count = 16

What is the first intermediate state in the baseline?

step: Step 1; previous: 25; state: 9; bit: 1

Why must p and q be distinct?

The intended Blum modulus is a product of distinct primes.

What condition must the seed satisfy?

It must be coprime to n.

Does a balanced output make small BBS parameters secure?

No.

06 · Knowledge assessment

Formative check

What is the output bit in this model?

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

Independent assessment

For p=11,q=19, seed=3, calculate x0 and the first five outputs; verify in Python. Repeat with seed=5 and compare empirical metrics without claiming security. 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 · CR32 →

How to investigate · CR31

Independent variable: seed 5 to 9; then p,q to 11,19.

Controlled variables: count and other parameters.

Dependent evidence: internal state, output bits and observed balance.

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

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