IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
ESSENTIAL LABORATORY · EC09 · IoT SECURITY AND PRIVACY
IoT Security and Privacy
RSA — Keys, modular exponentiation and encryption
Construct RSA public/private exponents from number theory, implement square-and-multiply, and verify encryption/decryption on bounded integer examples.
Construct RSA public/private exponents from number theory, implement square-and-multiply, and verify encryption/decryption on bounded integer examples.
The focus of this experiment is to derive textbook RSA parameters and modular exponentiation. Students then calculate and verify numerical encryption and decryption, and explain small-key and unpadded-RSA limitations. 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 textbook RSA parameters and modular exponentiation.
Calculate and verify numerical encryption and decryption.
Explain small-key and unpadded-RSA limitations.
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 textbook RSA parameters and modular exponentiation, calculate and verify numerical encryption and decryption, and explain small-key and unpadded-RSA limitations.
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 small-key and unpadded-RSA limitations. 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 PyCryptodome — AES-CTR, hashing and hash-chain PRNG.
Environment and experimental methodology
The included teaching workstation and the listed Python/Colab or WSL implementation. Historical and small-number constructions are instructional, not deployment recommendations.
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.
How to investigate RSA — Keys, modular exponentiation and encryption
Construct RSA public/private exponents from number theory, implement square-and-multiply, and verify encryption/decryption on bounded integer examples.
Analytical investigation means collecting an observation, identifying the mechanism, using a calculation or state trace to explain it, and checking your conclusion against evidence. Controlled comparison means changing one independent variable, holding the remaining relevant conditions constant, and measuring a dependent variable against a baseline. Experimental validation means comparing a predicted result to a reproducible observation or assertion; agreement inside a model does not certify hardware. Evidence-based reasoning connects a specific observation to a theoretical rule and states uncertainty, not merely an opinion. Performance characterization records a named metric and its units across conditions; sensitivity analysis changes one parameter across several values. A threat assessment links an asset, threat, consequence and evidence to a mitigation.
Experiment-specific guided practice
Objective: Construct RSA public/private exponents from number theory, implement square-and-multiply, and verify encryption/decryption on bounded integer examples.
Complete the analytical preparation below before programming. Show the intermediate mathematical calculations.
Square-and-multiply implementation — complete its numbered steps and record the requested evidence.
RSA key generation — complete its numbered steps and record the requested evidence.
RSA peer exchange and validation — complete its numbered steps and record the requested evidence.
Reference check: n=2077; φ=1980; e=7 is permitted and d=283; 12 encrypts to 1481 and decrypts to 12.
Model boundary: Fictional educational inputs. Browser algorithms and reference programs; no hardware or live-network measurements. Supplied starter notebooks may be incomplete; trace playback is recorded execution, not arbitrary Python running in browser.
Independent task and submission evidence
2. Square-and-multiply implementation — complete its numbered steps and record the requested evidence. Record the named input, prediction, actual output and one limitation; restore the original condition and repeat.
Before execution write the independent variable and its levels, dependent observation with units where applicable, baseline, controlled variables, measurement method and expected result. For a state machine use state/event/output rather than inventing a numeric metric. Record failures and repeat the baseline. A weak conclusion is “it works”; a supported conclusion names the changed setting, observed value/state, corresponding rule and one limitation.
Trial
Changed setting
Fixed settings
Predicted result
Actual observation / units
Evidence / uncertainty
A: baseline
Reference
Record
Predict
Record
Record
B: one change
Record
Same as A
Predict
Record
Record
A: repeat
Restore
Same as A
Predict
Record
Record
Completion: submit the filled table, relevant simulator screenshot or terminal/notebook output, reasoning with units/assumptions, and one limitation. Preserve the independent assessment questions; this guide does not fill their answers.
Scientific concept map: Primes p,q — n=pq; Totient — (p−1)(q−1); Public exponent — gcd(e,φ)=1; Private exponent — d=\(e^{-1}\) mod φ; Modular power — Encrypt / decrypt.
RSA key construction
For distinct primes p and q, form n=pq and φ(n)=(p−1)(q−1). Select e coprime to φ(n), then compute d=\(e^{-1}\) mod φ(n). The public pair is (n,e); d and the primes remain private. Never reuse classroom primes in a deployed system.
Modular exponentiation
Compute c=m^e mod n and recover m=c^d mod n for integer messages 0≤m<n. Square-and-multiply reads exponent bits, repeatedly squares and conditionally multiplies, reducing modulo n after each step. This avoids constructing huge intermediate powers.
Security boundary
Textbook RSA is deterministic and does not provide secure general-purpose encryption. Practical designs use standardized padding such as OAEP for encryption; signing uses a separate signature construction. In this lab, the small and large integers are public calculation fixtures.
Prerequisites: EC08 and earlier foundations as applicable.
Algorithm structure and data flow. Use the simulation to inspect the corresponding numerical transformations.
Engineering diagrams
RSA key construction and exponentiation.
Scientific foundations and worked examples
Number-theoretic key construction
For p=11,q=3, n=33 and φ=20. The permitted nontrivial e values in [2,19] are 3,7,9,11,13,17,19. Choosing e=3 gives d=7 because 3×7≡1 modulo 20. Encrypt M=8 as \(8^{3}\) mod 33=17; decrypt \(17^{7}\) mod 33=8. For general RSA the exponent inverse may also be computed modulo λ(n), the least common multiple of p−1 and q−1. Classroom integer messages must satisfy 0≤M<n.
Square-and-multiply worked examples
Scan exponent bits from left to right, starting with r=1. For each bit square r modulo n; if the bit is 1, multiply by the base modulo n. For \(5^{20}\) mod 35, 20=10100₂ and successive residues are 5,25,10,30,25. For \(275^{131}\) mod 277, 131=128+2+1; the powers at 128 and 2 are 155 and 4, so the final residue is 145. This takes O(log e) modular multiplications rather than O(e) naive multiplications.
Why mathematical RSA is not a deployed protocol
The raw RSA map is deterministic and multiplicatively structured. Secure encryption requires a standardized encoding such as OAEP and signatures use a distinct standardized scheme such as PSS. Modulus size, random key generation, private-key storage and side-channel protections are essential in production. Never use the small classroom keys for protection.
Engineering principles · additional worked teaching example
Textbook RSA chooses distinct primes p,q, n=pq and e coprime to φ=(p−1)(q−1). For p=3,q=11,e=3, φ=20, d=7 since 3×7=21≡1. Raw RSA is deterministic and lacks secure encoding; practical encryption uses OAEP.
From theory to experiment
Predict the reference result before operating the workbench; check the actual intermediate state, units and constraints. The existing simulation, implementation and procedure below are distinct sources of evidence.
Worked engineering reasoning and boundary conditions
RSA uses n=pq, φ=(p−1)(q−1), gcd(e,φ)=1 and ed≡1 mod φ. Toy primes are for hand calculations only. For p=5,q=11,e=3,d=27.
Use the diagram to follow the calculation or state progression. Keep the teaching configuration separate from the independent exercise values; compare observations with the actual model and implementation.
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.
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.
Step 1 of 4 · Toy primes
Toy primes
Toy primes
p=5, q=11
Modulus and totient
Toy primes
p=5, q=11
Modulus and totient
n=55, φ=40
Public exponent
Toy primes
p=5, q=11
Modulus and totient
n=55, φ=40
Public exponent
e=3
Private exponent
Toy primes
p=5, q=11
Modulus and totient
n=55, φ=40
Public exponent
e=3
Private exponent
d=27; 3×27=81≡1 mod 40
Teaching example only; inspect live calculations or real practical evidence separately.
Interactive flashcards
Self-rated study progress is stored locally, not used for official grades.
Browse all explanationsWhat is RSA modulus?
Product of two primes.
Why must e be coprime to the totient?
To permit a modular inverse for the private exponent.
What does square-and-multiply do?
Efficient modular exponentiation.
Why avoid textbook RSA?
It lacks secure padding and is deterministic.
What is the RSA modulus?
n=pq for two primes.
What is φ(n) for distinct primes p and q?
(p−1)(q−1).
What condition must e meet?
gcd(e,φ(n))=1, with e in the permitted range for the teaching construction.
How is d calculated?
The modular inverse of e modulo φ(n) in this lab.
What is textbook RSA encryption?
c=m^e mod n.
What is textbook RSA decryption?
m=c^d mod n.
Why must the integer message be smaller than n?
RSA operates on residues modulo n.
How does square-and-multiply process an exponent?
Square the running value and multiply for set exponent bits under the chosen convention.
Why not use raw RSA in production?
It is deterministic and lacks secure randomized encoding.
What scheme is used for secure RSA encryption in the capstone?
RSA-OAEP with an appropriate hash.
Take p=5, q=11 and e=3. Is e valid?
λ(55)=lcm(4,10)=20; gcd(3,20)=1, so e is invertible modulo λ(n). These tiny primes are teaching values only.
Why reduce after each square or multiplication?
Modular reduction preserves the final residue while avoiding huge intermediate integers.
Why is textbook RSA unsafe for encrypting arbitrary real messages?
It is deterministic and lacks a secure encoding. Use a standardized padding scheme such as OAEP for encryption.
Choose a workstation, edit the inputs, and observe recalculated results. Play or step through the actual calculation trace. Hash-search stations calculate successive candidates during playback. All inputs are fictional training data.
Where the browser requires Web Crypto, launch the local portal on localhost or use the HTTPS deployment. The classroom algorithms and keys are not intended for production use.
Independent theoretical exercises
Complete every question independently on paper or in the fields below before using the simulation or programming activities. Show formulas, intermediate steps, tables, proofs and units. Afterward verify your work using the simulator and Python, and explain discrepancies. Worked examples in Concepts do not replace your own derivation.
01 · Original pen-and-paper RSA
Take p=31 and q=67. Calculate n and φ(n); choose a valid e among 5,7,11 and justify it. Find d by extended Euclid. Encrypt M=12 and recover it by square-and-multiply. Show the complete tables.
Engineering method — Textbook RSA chooses distinct primes p,q, n=pq and e coprime to φ=(p−1)(q−1). For p=3,q=11,e=3, φ=20, d=7 since 3×7=21≡1. Raw RSA is deterministic and lacks secure encoding; practical encryption uses OAEP. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
02 · Square-and-multiply
Show the algorithm with a small example and explain its complexity. Use the original large c1,c2 operands in the practical activity for computational verification, not direct exponentiation.
Engineering method — Textbook RSA chooses distinct primes p,q, n=pq and e coprime to φ=(p−1)(q−1). For p=3,q=11,e=3, φ=20, d=7 since 3×7=21≡1. Raw RSA is deterministic and lacks secure encoding; practical encryption uses OAEP. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
03 · Large-key exercise
Using the assigned large primes in the existing activity, specify how to derive n, φ, e and d. Explain why shared supplied primes are for teaching only and why production RSA needs independent secure prime generation and padding.
Engineering method — Textbook RSA chooses distinct primes p,q, n=pq and e coprime to φ=(p−1)(q−1). For p=3,q=11,e=3, φ=20, d=7 since 3×7=21≡1. Raw RSA is deterministic and lacks secure encoding; practical encryption uses OAEP. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
04 · Peer exchange
Use a fictional numeric message within the valid range, exchange public keys, encrypt and verify recovery; explain what raw RSA does not guarantee.
Engineering method — Textbook RSA chooses distinct primes p,q, n=pq and e coprime to φ=(p−1)(q−1). For p=3,q=11,e=3, φ=20, d=7 since 3×7=21≡1. Raw RSA is deterministic and lacks secure encoding; practical encryption uses OAEP. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
05 · Calculation
Calculation · Independent work
For p=7,q=11,e=7, derive n,φ,d and encrypt m=2; verify recovery by modular exponentiation.
Calculation — Textbook RSA chooses distinct primes p,q, n=pq and e coprime to φ=(p−1)(q−1). For p=3,q=11,e=3, φ=20, d=7 since 3×7=21≡1. Raw RSA is deterministic and lacks secure encoding; practical encryption uses OAEP. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
Responses are saved locally when browser storage is available. Export your work for submission. No automatic grading or remote upload occurs.
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.
Foundational · Apply the principle
Independent theoretical exercise · EC09-01
With p=7,q=13 calculate n and φ.
Intermediate · Calculate or trace
Independent theoretical exercise · EC09-02
Check e=5 and calculate d modulo 72.
Intermediate · Interpret the result
Independent theoretical exercise · EC09-03
Encrypt m=2 using e=5,n=91.
Advanced · Analyze a condition
Independent theoretical exercise · EC09-04
Explain why choosing e=6 for φ=72 fails.
Advanced · Diagnose or compare
Independent theoretical exercise · EC09-05
What is the allowable integer message interval for raw RSA n=91?
Challenging · Engineering verification
Independent theoretical exercise · EC09-06
Why should a signature not be described as encrypting a message with a private key?
Activity sequence
Follow the setup commands, then each named activity. The detailed instructions, given values and recording fields appear below.
Complete the analytical preparation below before programming. Show the intermediate mathematical calculations.
Use distinct primes; keep message in [0,n); verify gcd(e,φ)=1 before encryption.
Validation and evidence
Before running a trial, predict its output. Use the baseline conditions below to check your method, then vary one independent variable. Save calculated outputs or the actual Python trace. Keep browser results and local Python execution distinct.
Trial
Controlled configuration
Reference check
Student observation (editable)
Small fixture
p=31,q=67,e=7,m=12
n=2077, d=283, c=1481, recovered 12
Enter observation
Invalid exponent
e sharing a factor with φ
Reject key
Enter observation
Large fixture
Supplied c1,c2
Compare square-and-multiply with pow(c1,c1,c2); never compute c1**c1 directly
Enter observation
Analysis: Report exponent bit operations and correctness separately from execution time. This is textbook RSA, not an OAEP or production security test.
Construct RSA public/private exponents from number theory, implement square-and-multiply, and verify encryption/decryption on bounded integer examples.
Equipment and execution
Browser-based simulator, Python 3, notebook or local evidence folder. Use WSL Setup only if you need a Linux runtime.
2. Follow these commands in sequence (Linux/WSL). For browser-only activities, open Simulation first; the code activities are independent.
BASH · Command
cd code
python lab09.py
3. Run the check before changing inputs. Record the exact Python version and any dependency error. Use Python visualizer to inspect the recorded traces; for edited code, generate and import a new trace using the instructions in that tab.
Complete the activities in order. Hold the controlled conditions fixed, record the input and actual output, and compare your observations with an independent calculation or test vector.
01
Square-and-multiply implementation
Open the exact workstation
Choose the relevant tab below, enter the assigned values in the activity steps, then use Step or Play to inspect intermediate calculations. Return to Experiment and record the results before changing the input.
Complete the Python task pen-and-paper problem: p=31, q=67, choose e from 5, 7, 11, justify your choice, compute d and encrypt/decrypt 12. Reuse the GCD/inverse helpers.
Implement sqm(base, exponent, modulus) using exponent bits, squaring and conditional multiplication with modular reduction. Reproduce the small worked example.
Run the exact large c1,c2 fixture below using sqm(c1,c1,c2). Compare against the fixture check value and Python pow(c1,c1,c2).
Measure naive vs modular exponentiation only on safe small exponents; never execute c1**c1. Use Python Visualizer to inspect a small trace.
Download the public integer fixture if you prefer to load the long operands from JSON. Compare the result with Python pow(c1, c1, c2); never compute the unreduced power.
Bit sequence, accumulator trace, large-fixture equality and bounded timing.
Verification: Record the baseline and modified input separately, note the observed intermediate values, compare with the assigned calculation, and explain any mismatch. Do not replace observations with expected values.
02
RSA key generation
Open the exact workstation
Choose the relevant tab below, enter the assigned values in the activity steps, then use Step or Play to inspect intermediate calculations. Return to Experiment and record the results before changing the input.
Reproduce p=11,q=3,e=3, n=33, φ=20, d=7 and test encryption/decryption.
Load the large primes p,q below; compute n, φ and choose e relatively prime to φ. Compute d with extended Euclid and verify ed mod φ=1.
Share only public (n,e) with a lab partner; use fictional numeric IDs and do not share private d.
Key-generation calculations and verified inverse (demo keys only).
Verification: Record the baseline and modified input separately, note the observed intermediate values, compare with the assigned calculation, and explain any mismatch. Do not replace observations with expected values.
03
RSA peer exchange and validation
Open the exact workstation
Choose the relevant tab below, enter the assigned values in the activity steps, then use Step or Play to inspect intermediate calculations. Return to Experiment and record the results before changing the input.
Choose a fictional message integer below recipient n; encrypt with the partner public exponent using sqm.
Decrypt the received ciphertext using your own d. Verify recovered message and reject messages outside [0,n).
Explain the limitations of textbook RSA and compare with the optional OAEP workstation.
Evidence to record
Outgoing/received ciphertext, recovered message and negative control.
Verification: Record the baseline and modified input separately, note the observed intermediate values, compare with the assigned calculation, and explain any mismatch. Do not replace observations with expected values.
Challenge data and additional questions
Public square-and-multiply fixture (copy the integers into the simulator or use the downloadable JSON):
c1 = 18681427692158875519487088075483659952350784095426850535886777025764383119115214958422688170629212939425578696612104065278836818480205439611172533343162586565318046086821649841855655529786476912936117
c2 = 23262524066749752930003794793282025892156162339903512977981352192237243527808339996497055361739127886746797334866642423823838668793093810257339868397178981443559849998387464783404753032562620423782819
p = 879444170374861669641134196218346212695898251128878861274462696397360027254709043134636220593750949647657696083593011526569499231402671759015715247847100292170454549945387184247594207004818786761105412070559714186375611091845523065678013356121887671718894703109758066601977029635298290603841128648803
q = 498123355539734090651342024511099831516304715462262346470827576945203575116701551738041914223749202101027640044384914081312728700908681008628987214128029359450401447589262841875627065956937931557006312756303050952146176840242929855061267653489429686714147273857523203781398260195342718507985441066291
expected = 18893848484910893511651955280078076958941196161921459889477875989317545794888006358946285424288705798102332802958419106114772669466253753323533760293102323766166217151771107318063024426773397636029732
Download this notebook and open Google Colab. Select File → Upload notebook and choose the downloaded .ipynb.
Read the Markdown instructions before each executable cell. Use a Python runtime, run cells from top to bottom, and resolve imports if necessary.
Perform the baseline and controlled changes. Save the notebook with actual outputs and your written interpretation.
Execution scope: Fictional educational inputs. Browser algorithms and reference programs; no hardware or live-network measurements. Supplied starter notebooks may be incomplete; trace playback is recorded execution, not arbitrary Python running in browser. Default computational cells passed isolated local Python execution; physical equipment and live services require separate verification.
01Instructions · Markdown
# EC09 · RSA — Keys, modular exponentiation and encryption
**PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh**
## 1. Scientific objective
Follow the setup commands, then each named activity. The detailed instructions, given values and recording fields appear below.
Complete the analytical worksheet in the portal first. Record your predictions before running this notebook. This notebook is a bounded local computational investigation; use the portal’s separate WSL, hardware or Remix procedure for real interfaces.
02Instructions · Markdown
## Experiment-specific preparation
Construct RSA public/private exponents from number theory, implement square-and-multiply, and verify encryption/decryption on bounded integer examples.
**Reference procedure (use the matching simulator/WSL tool where named, not an unrelated service):**
1. Complete the analytical preparation below before programming. Show the intermediate mathematical calculations.
2. Square-and-multiply implementation — complete its numbered steps and record the requested evidence.
3. RSA key generation — complete its numbered steps and record the requested evidence.
4. RSA peer exchange and validation — complete its numbered steps and record the requested evidence.
5. Compare observations with the reference checks and submit the required evidence.
**Evidence:** n=2077; φ=1980; e=7 is permitted and d=283; 12 encrypts to 1481 and decrypts to 12.
**Boundary:** Fictional educational inputs. Browser algorithms and reference programs; no hardware or live-network measurements. Supplied starter notebooks may be incomplete; trace playback is recorded execution, not arbitrary Python running in browser.
03Instructions · Markdown
## 2. Reference configuration and investigation
1. Complete the analytical preparation below before programming. Show the intermediate mathematical calculations.
2. Square-and-multiply implementation — complete its numbered steps and record the requested evidence.
3. RSA key generation — complete its numbered steps and record the requested evidence.
4. RSA peer exchange and validation — complete its numbered steps and record the requested evidence.
5. Compare observations with the reference checks and submit the required evidence.
Run cells in order; do not substitute model results for physical measurements.
04Instructions · Markdown
### Dependency — lab04
The following cells define the actual toolkit dependency.
05Instructions · Markdown
Dependency definitions 1
06Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC09 | Code cell 01 | RSA — Keys, modular exponentiation and encryption
# Purpose: Dependency definitions 1
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
"""Essential 04 — Euclid, totient, Affine and Hill cipher primitives."""
from math import gcd
from string import ascii_uppercase as A
# Define the reusable operation extendedGCD; keep its logic separate from the trial.
def extendedGCD(a,b):
x,y,u,v=1,0,0,1
while b:
q,r=divmod(a,b); a,b=b,r; x,u=u,x-q*u; y,v=v,y-q*v
return (a,x,y) if a>=0 else (-a,-x,-y)
# =====================================================================
# EC09 | Code cell 02 | RSA — Keys, modular exponentiation and encryption
# Purpose: Dependency definitions 2
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Define the reusable operation inverseMod; keep its logic separate from the trial.
def inverseMod(a,m):
if m<2: raise ValueError('Modulus must exceed one')
d,s,_=extendedGCD(a,m)
if d!=1: raise ValueError('No modular inverse')
return s%m
# Define the reusable operation primeFactors; keep its logic separate from the trial.
def primeFactors(n):
if n<2: raise ValueError('n must be ≥2')
result=[]; d=2
while d*d<=n:
while n%d==0: result.append(d); n//=d
d+=1
if n>1: result.append(n)
return result
# Define the reusable operation eulerTotient; keep its logic separate from the trial.
def eulerTotient(n):
result=n
for p in set(primeFactors(n)): result=result//p*(p-1)
return result
# =====================================================================
# EC09 | Code cell 03 | RSA — Keys, modular exponentiation and encryption
# Purpose: Dependency definitions 3
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Define the reusable operation sqm; keep its logic separate from the trial.
def sqm(a,e,m):
if e<0 or m<2: raise ValueError('Invalid exponent or modulus')
value=1; a%=m
while e:
if e&1: value=value*a%m
a=a*a%m; e//=2
return value
# Define the reusable operation affine; keep its logic separate from the trial.
def affine(text,a,b,decrypt=False):
inverse=inverseMod(a,26)
return ''.join(A[(inverse*(A.index(c)-b) if decrypt else a*A.index(c)+b)%26] for c in text.upper() if c in A)
# Define the reusable operation inverseMatrixMod; keep its logic separate from the trial.
def inverseMatrixMod(k,m):
a,b=k[0]; c,d=k[1]; z=inverseMod(a*d-b*c,m)
return [[d*z%m,-b*z%m],[-c*z%m,a*z%m]]
# =====================================================================
# EC09 | Code cell 04 | RSA — Keys, modular exponentiation and encryption
# Purpose: Dependency definitions 4
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Define the reusable operation hill; keep its logic separate from the trial.
def hill(text,k,alphabet=A,decrypt=False):
m=len(alphabet); inv=inverseMatrixMod(k,m); k=inv if decrypt else k
text=''.join(c for c in text.upper() if c in alphabet)
if len(text)%2:
if decrypt: raise ValueError('Odd ciphertext length')
text+='X'
out=[]
for i in range(0,len(text),2):
x,y=map(alphabet.index,text[i:i+2]); out.extend(alphabet[(r[0]*x+r[1]*y)%m] for r in k)
return ''.join(out)
# =====================================================================
# EC09 | Code cell 05 | RSA — Keys, modular exponentiation and encryption
# Purpose: Dependency definitions 4
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
import types, sys
# Set _dependency for the next computation or reference condition.
_dependency = types.ModuleType('lab04')
_dependency.__dict__.update({k:v for k,v in globals().copy().items() if not k.startswith("__")})
# Set sys.modules['lab04'] for the next computation or reference condition.
sys.modules['lab04'] = _dependency
## 3. Algorithm implementation
Read each definition and relate it to the equations and scientific SVGs in Concepts.
15Instructions · Markdown
### Implementation cell 1
Inspect the definitions, then execute to make them available for the investigation.
16Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC09 | Code cell 06 | RSA — Keys, modular exponentiation and encryption
# Purpose: Implementation cell 1 Inspect the definitions, then execute to make them available for the investigation.
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
"""Essential 09 — textbook RSA for number-theory exercises only."""
import json
from pathlib import Path
from math import gcd
from lab04 import sqm,inverseMod
# Define the reusable operation rsa numbers; keep its logic separate from the trial.
def rsa_numbers(p,q,e):
if p==q or p<2 or q<2: raise ValueError('Distinct primes required; supplied fixtures are public')
phi=(p-1)*(q-1)
if not 1<e<phi or gcd(e,phi)!=1: raise ValueError('Invalid exponent')
return p*q,inverseMod(e,phi)
## 4. Execute reference controls
The program checks selected algorithm outcomes. Record the observed output. These checks do not replace the independent calculation assignment.
18Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC09 | Code cell 07 | RSA — Keys, modular exponentiation and encryption
# Purpose: 4. Execute reference controls The program checks selected algorithm outcomes. Record the observed output. These checks do not replace the independent calculation assignment.
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Set (n, d) for the next computation or reference condition.
n, d = rsa_numbers(31, 67, 7)
# Set c for the next computation or reference condition.
c = sqm(12, 7, n)
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert (n, d, c) == (2077, 283, 1481) and sqm(c, d, n) == 12
# Set fixture for the next computation or reference condition.
fixture = {'c1': '18681427692158875519487088075483659952350784095426850535886777025764383119115214958422688170629212939425578696612104065278836818480205439611172533343162586565318046086821649841855655529786476912936117', 'c2': '23262524066749752930003794793282025892156162339903512977981352192237243527808339996497055361739127886746797334866642423823838668793093810257339868397178981443559849998387464783404753032562620423782819', 'p': '879444170374861669641134196218346212695898251128878861274462696397360027254709043134636220593750949647657696083593011526569499231402671759015715247847100292170454549945387184247594207004818786761105412070559714186375611091845523065678013356121887671718894703109758066601977029635298290603841128648803', 'q': '498123355539734090651342024511099831516304715462262346470827576945203575116701551738041914223749202101027640044384914081312728700908681008628987214128029359450401447589262841875627065956937931557006312756303050952146176840242929855061267653489429686714147273857523203781398260195342718507985441066291', 'expected': '18893848484910893511651955280078076958941196161921459889477875989317545794888006358946285424288705798102332802958419106114772669466253753323533760293102323766166217151771107318063024426773397636029732'}
# Set (x, m) for the next computation or reference condition.
x, m = (int(fixture['c1']), int(fixture['c2']))
# Set expected for the next computation or reference condition.
expected = int(fixture['expected'])
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert sqm(x, x, m) == pow(x, x, m) == expected
# Set (p, q) for the next computation or reference condition.
p, q = (int(fixture['p']), int(fixture['q']))
# Set phi for the next computation or reference condition.
phi = (p - 1) * (q - 1)
# Set e for the next computation or reference condition.
e = 65537
while gcd(e, phi) != 1:
e += 2
# Set (n, d) for the next computation or reference condition.
n, d = rsa_numbers(p, q, e)
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert sqm(sqm(12345, e, n), d, n) == 12345
print('Small and public large-fixture RSA checks passed')
## 5. Controlled variation
Predict the effect of the parameter changes below. Compare each actual result to your prediction.
20Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC09 | Code cell 08 | RSA — Keys, modular exponentiation and encryption
# Purpose: 5. Controlled variation Predict the effect of the parameter changes below. Compare each actual result to your prediction.
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Repeat the same operation for each configured input so observations are comparable.
for e in (5,7,11):
print(e,gcd(e,1980))
## Experimental analysis and submission
1. Record the reference input, predicted output and actual result.
2. Modify one independent variable and run the relevant cells again.
3. Explain the result using the theory and identify model limitations.
4. Save the notebook with outputs and retain the separate theoretical worksheet.
**Your derivation and conclusion:**
(Complete independently.)
22Instructions · Markdown
## Guided reasoning and evidence
A controlled comparison changes one independent input while keeping the other relevant inputs fixed; the dependent variable is the recorded output. Use this lab’s reference condition above.
**Independent task:** 2. Square-and-multiply implementation — complete its numbered steps and record the requested evidence. Record the named input, prediction, actual output and one limitation; restore the original condition and repeat.
| Trial | Input/configuration | Prediction | Observation | Evidence / limitation |
|---|---|---|---|---|
| A | Reference | | | |
| B | Changed input | | | |
| A repeat | Reference | | | |
A conclusion is supported only when it cites the recorded values or observed states and explains them with the experiment theory.
Python implementation
Download the complete practical toolkit and extract it to a new directory. Keep the code and challenges folders together.
Explore actual CPython execution traces from the included laboratory programs. Play, pause, step, inspect the current line, local variable values, function call stack, return values and output. Green variable cells changed relative to the preceding event. Line events show state before the highlighted line executes.
Run and visualize your own modified Python program
Download the Essential Cryptography Toolkit, extract it, and open a terminal in its code directory. Run the worked example or edit a copy. The trace generator executes your actual local Python file and creates an importable JSON record. Only run trusted code and use fictional keys and data.
Choose Import your trace in the visualizer and select my-trace.json. This works offline; the portal does not execute arbitrary Python on its server. The optional external Python Tutor link is suitable for standalone standard-library code, but external dependencies or local imports may not work.
For AES/DES exercises, install either supported cryptographic backend in an isolated Python environment as described in the Python code tab. Native library internals are not traced; the algorithm-specific browser workstations display the intermediate mathematics.
Why is modular exponentiation more efficient than evaluating a**e first?
Why should textbook RSA not be used directly in production?
Submission: Submit key calculations, modular exponentiation traces, fixture cross-check and a successful round trip.
Export actual calculated observations from each workstation. Record your own predictions and conclusions, and distinguish browser calculations from local or physical measurements.
Shared research workbenches · network designer & advanced studiesConcurrent-device simulation & Monte Carlo research