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 · CR45 · RSA
IoT Security and Privacy

RSA manual key generation

Derive the RSA key pair.

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

Scope and objectives

Scope of the experiment

RSA uses distinct primes to construct a composite modulus. Knowledge of the factorization permits computation of a private exponent; public information includes n and e.

The focus of this experiment is to compute RSA modulus and totient from distinct primes. Students then validate e and derive the private exponent using EEA, and verify ed modulo the totient and explain why toy keys are insecure. 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

  • Compute RSA modulus and totient from distinct primes.
  • Validate e and derive the private exponent using EEA.
  • Verify ed modulo the totient and explain why toy keys are insecure.
  • 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 compute RSA modulus and totient from distinct primes, validate e and derive the private exponent using EEA, and verify ed modulo the totient and explain why toy keys are insecure.

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 ed modulo the totient and explain why toy keys are insecure. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to RSA encryption and decryption.

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

CR45 · RSA manual key generation

For distinct odd primes p and q, n=pq and φ(n)=(p−1)(q−1). Choose 1<e<φ(n) with gcd(e,φ)=1. The extended Euclidean algorithm finds d such that e·d≡1 mod φ. Small classroom primes are not secure.

Learning objectives

Derive the RSA key pair. Predict a result, inspect intermediate states, verify the invariant and explain the specified boundary case.

Prerequisites

Before starting

Environment: standard computer, browser and Python/WSL.

Simulation: live bounded classroom calculations in the browser and Python.

Technical scope: Small synthetic parameters; educational mathematics, not production cryptography.

Complete the six stages in order. Use the same experiment inputs when comparing manual, browser and Python results.

02 · Concepts and mathematical foundations

For distinct odd primes p and q, n=pq and φ(n)=(p−1)(q−1). Choose 1<e<φ(n) with gcd(e,φ)=1. The extended Euclidean algorithm finds d such that e·d≡1 mod φ. Small classroom primes are not secure.

Learning objectives

Derive the RSA key pair. Predict a result, inspect intermediate states, verify the invariant and explain the specified boundary case.

Prerequisites

Mathematical verification and controlled comparison

Substitute the output into its defining equation or check the protocol invariant. A controlled comparison changes one input while holding others fixed. Cite actual trace values and identify the limitations of the evidence.

Before starting

Environment: standard computer, browser and Python/WSL.

Simulation: live bounded classroom calculations in the browser and Python.

Technical scope: Small synthetic parameters; educational mathematics, not production cryptography.

RSA key generation

1 · Principles and purpose

RSA uses distinct primes to construct a composite modulus. Knowledge of the factorization permits computation of a private exponent; public information includes n and e.

2 · Mathematical and algorithmic foundations

n=pq; φ=(p−1)(q−1); choose e with 1<e<φ and gcd(e,φ)=1; d=\(e^{-1}\) mod φ. For p=5,q=11,e=3, φ=40 and 1=40−13·3, so d=−13≡27.

3 · Worked teaching example

Check 3·27=81≡1 mod40. Small examples and raw RSA are instructional; deployed RSA uses approved key generation and encoding.

Verified default trace · 5 intermediate states

Given parameters (teaching example):

{
  "p": 5,
  "q": 11,
  "e": 3
}
StageComputed values
1{ "n": 55, "phi": 40, "gcd": 1 }
2{ "dividend": 3, "divisor": 40, "quotient": 0, "remainder": 3, "coeff_a": 1, "coeff_b": 0 }
3{ "dividend": 40, "divisor": 3, "quotient": 13, "remainder": 1, "coeff_a": -13, "coeff_b": 1 }
4{ "dividend": 3, "divisor": 1, "quotient": 3, "remainder": 0, "coeff_a": 40, "coeff_b": -3 }
5{ "e": 3, "d": 27, "product_mod_phi": 1 }

Recorded result

{
  "public": [
    3,
    55
  ],
  "private": [
    27,
    55
  ],
  "phi": 40
}

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

RSA key equations

Distinct primes p,q determine the modulus n; e is public and d private. Textbook m is an integer in [0,n). Small raw RSA is solely an arithmetic teaching model; real encryption uses a vetted padding scheme.

\[\begin{aligned}n&=pq,&\varphi(n)&=(p-1)(q-1)\\\gcd(e,\varphi(n))&=1,&ed&\equiv1\pmod{\varphi(n)}\\c&=m^e\bmod n,&m&=c^d\bmod n\end{aligned}\]

Concept animation · RSA key dependency

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.

Choose primesp = 11q = 13Derive modulus and totientp = 11q = 13n = 143φ = 120Choose public exponentp = 11q = 13n = 143φ = 120e = 7Invert the exponentp = 11q = 13n = 143φ = 120e = 7d = 103Public key(143, 7)

Step 1 of 4 · Choose primes

Choose primes

Choose distinct teaching primes 11 and 13.

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…

Reference SVG (visible without scripts). Use the editable workstation below to calculate or run the experiment.
RSA key derivation · n, φ(n), Euclidean chain and dRSA key derivation · n, φ(n), Euclidean chain and dp × q5 × 11Modulus n55Totient φ40Public e3gcd(e, φ)1Private d27e·d mod φ1Distinct primes; gcd(e, φ) = 1; inverse gives the private exponent.

Choose a reference trial or edit the parameters. The workstation computes new results; practical cryptography uses Web Crypto when available and labels recorded Python references separately.

Verified baseline reference

Calculated result or labeled reference

{
  "public": [
    3,
    55
  ],
  "private": [
    27,
    55
  ],
  "phi": 40
}
Complete trace

Dr. Mohammad · contextual guide

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

p=5, q=11, e=3: n=55, φ=40, 40=13·3+1, so 1=40−13·3 and d=−13 mod 40=27. Verify 3·27 mod 40=1.

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

Select p=7, q=11 and e=7. Calculate n and φ, verify gcd(e,φ)=1 and derive d by EEA. Explain why e=10 is invalid for this example.

02 · RSA calculation

RSA calculation · Independent work

Choose p=11, q=13, e=7. Derive n, φ(n), gcd(e, φ(n)) and d. Verify e·d ≡ 1 (mod φ(n)); explain why the classroom key is unsuitable for production.

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

For the separate teaching-test configuration p: 5; q: 11; e: 7, predict phi 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 · CR45-02

A teaching trace for RSA manual key generation contains dividend: 3; divisor: 40; quotient: 0; remainder: 3; coeff_a: 1. Explain the role of coeff_b (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 · CR45-03

The first teaching trace contains n: 55; phi: 40; gcd: 1; the last contains e: 3; d: 27; product_mod_phi: 1. 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 · CR45-04

Plan a comparison of p: 5; q: 11; e: 3 with p: 5; q: 11; e: 7. Record the dependent value public, 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; run the integrated workstation or extracted toolkit. All classroom calculations run locally.

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

Derive the RSA key pair

  1. Write a prediction based on the worked example.
  2. Calculate n and φ manually; trace the Euclidean chain and derive d from Bézout’s coefficient.
  3. Export the trace and compare the result with the reference.

Experimental inputs

Experimental reference · json
{"p":5,"q":11,"e":3}
Verified baseline reference (check after predicting)
Experimental reference · json
{"public":[3,55],"private":[27,55],"phi":40}

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, φ, quotient/remainder table, Bézout coefficients, d and e·d mod φ.

Run baseline →
02

Part D · Controlled investigation — Derive the RSA key pair

  1. Set e=7 with p,q fixed. Then try e=10 and record the rejection. Restore e=3 and change q to 17. Explain the change in φ and d.
  2. Record fixed settings and complete the comparison table.
  3. Measure n, φ, quotient/remainder table, Bézout coefficients, d and e·d mod φ. Explain the first differing state or invariant.
TrialInput configurationPredictionObservedVerification
1{"p":5,"q":11,"e":3}
2{"p":5,"q":11,"e":7}
3{"p":5,"q":17,"e":3}

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. Use python3 lab.py --inputs followed by the JSON from a trial. Compare exact math; for randomized or timed experiments compare invariants and report actual measurements separately.
  3. Complete the independent assessment below without copying the worked baseline. Explain discrepancies and distinguish mathematical results from security claims.
Additional investigation instructions
  1. Read the theory and prerequisite labs. Run the baseline and record the input and result.
  2. Compare e=3 and e=7. Try e=10 in Python and explain why it must be rejected.
  3. Locate the first intermediate step where the two cases differ. Verify the defining equation or decision rule.
  4. Submit a two-row comparison table, trace evidence and a conclusion with limitations.
CaseInputObserved resultVerificationLimitation
BaselineRecordRecordDeriveExplain
ChangedRecordRecordDeriveExplain

Part C · Python, Google Colab and WSL

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 CR45
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 --inputs "$(cat 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 --inputs "$(cat 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: # Python standard library only

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 CR45/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": {
    "n": 55,
    "phi": 40,
    "gcd": 1
  },
  "result": {
    "public": [
      3,
      55
    ],
    "private": [
      27,
      55
    ],
    "phi": 40
  }
}

Test script output:
CR45 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.

Download the notebook, open Google Colab and upload it using File → Upload notebook. For local Linux/WSL execution, follow the command blocks below in order.

Inspect Python source
Documented Python implementation · python
# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR45
# Experiment: rsa manual key generation
# Purpose: expose algorithm states and verify the experiment invariant.
# ------------------------------------------------------------
# CR45 | RSA manual key generation
# Execute the named operation; expose states and assert the laboratory invariant.
import math
import json

def egcd(a,b):
    # Track coefficients of a and b alongside the successive remainders.
    r,s,t=a,1,0; nr,ns,nt=b,0,1; steps=[]
    while nr:
        q=r//nr; steps.append({'dividend':r,'divisor':nr,'quotient':q,'remainder':r%nr,'coeff_a':s-q*ns,'coeff_b':t-q*nt})
        r,nr=nr,r-q*nr; s,ns=ns,s-q*ns; t,nt=nt,t-q*nt
    return r,s,t,steps

def inv(a,m):
    g,x,_,_=egcd(a%m,m)
    if g!=1: raise ValueError('No inverse: gcd is not 1')
    return x%m

def prime(n):
    return n>=2 and all(n%i for i in range(2,math.isqrt(n)+1))

DEFAULT={'p': 5, 'q': 11, 'e': 3}
ALTERNATE={'e': 7}

def run(overrides=None):
    # Merge only explicitly supplied inputs with the reference baseline.
    params={**DEFAULT, **(overrides or {})}
    p=params['p']
    q=params['q']
    e=params['e']
    if not (type(p) is type(q) is type(e) is int and 3<=p<=997 and 3<=q<=997 and 1<e<(p-1)*(q-1)): raise ValueError('Invalid classroom RSA parameters')
    if p==q or not prime(p) or not prime(q):raise ValueError('distinct primes required')
    n=p*q;phi=(p-1)*(q-1);g,x,y,trace=egcd(e,phi);d=inv(e,phi)
    steps=[{'n':n,'phi':phi,'gcd':g}]+trace+[{'e':e,'d':d,'product_mod_phi':e*d%phi}];result={'public':[e,n],'private':[d,n],'phi':phi}
    # Independently check the stated mathematical or protocol invariant.
    assert result["public"][0]*result["private"][0]%result["phi"]==1, "verification failed"
    return {"steps":steps,"result":result}

if __name__ == "__main__":
    import argparse
    parser=argparse.ArgumentParser();parser.add_argument("--inputs",default="{}");parser.add_argument("--test",action="store_true");args=parser.parse_args()
    if args.test:
        for case in [{},ALTERNATE]:run(case)
        print("PASS")
    else:print(json.dumps(run(json.loads(args.inputs)),indent=2))
Baseline reference (randomized fields may vary)
Reference result · json
{
  "public": [
    3,
    55
  ],
  "private": [
    27,
    55
  ],
  "phi": 40
}

05 · Interactive flashcards

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

Browse all explanations
What is φ for p=5,q=11?

40.

Why is e=10 invalid?

gcd(10,40)=10.

What is d for e=3?

27; 81 mod 40=1.

Which condition ensures e has an inverse modulo φ?

gcd(e,φ)=1

What evidence should be recorded?

n, φ, quotient/remainder table, Bézout coefficients, d and e·d mod φ.

How should the comparison be controlled?

Set e=7 with p,q fixed. Then try e=10 and record the rejection. Restore e=3 and change q to 17. Explain the change in φ and d.

06 · Knowledge assessment

Set e=7 with p,q fixed. Then try e=10 and record the rejection. Restore e=3 and change q to 17. Explain the change in φ and d. Submit the stated measurements, a reasoned comparison and independent verification. Criteria: mathematical correctness 40%, reproducibility 30%, interpretation 20%, limitations 10%.

Formative knowledge check

Which condition ensures e has an inverse modulo φ?

Select one answer

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

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 · CR46 →