Implement and test modular-arithmetic helpers that can be reused in RSA and Hill cipher laboratories.
The focus of this experiment is to implement modular arithmetic as reusable Python functions. Students then trace Euclidean recursion and exponentiation with explicit preconditions, and verify results and handle invalid inverses or modulus inputs. 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
Implement modular arithmetic as reusable Python functions.
Trace Euclidean recursion and exponentiation with explicit preconditions.
Verify results and handle invalid inverses or modulus inputs.
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 implement modular arithmetic as reusable Python functions, trace Euclidean recursion and exponentiation with explicit preconditions, and verify results and handle invalid inverses or modulus inputs.
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 results and handle invalid inverses or modulus inputs. 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 DES — S-boxes, Feistel rounds and avalanche.
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 Modular arithmetic in Python — Reusable crypto functions
Implement and test modular-arithmetic helpers that can be reused in RSA and Hill cipher laboratories.
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: Implement and test modular-arithmetic helpers that can be reused in RSA and Hill cipher laboratories.
Complete the analytical preparation below before programming. Show the intermediate mathematical calculations.
Factorization, totient and GCD functions — complete its numbered steps and record the requested evidence.
Modular inverse and matrix utilities — complete its numbered steps and record the requested evidence.
Hill Python implementation — complete its numbered steps and record the requested evidence.
Reference check: primeFactors(24)=[2,2,2,3]; φ(24)=8; gcd(121,55)=11; the modular matrix inverse gives the identity.
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. Factorization, totient and GCD functions — 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: Integer or matrix — Function input; Recursive GCD — Base case / remainder; Modular inverse — Extended Euclid; Matrix product — Mod 26; Validation — Identity / round trip.
Reusable integer utilities
Build small Python functions for factorization, totient, iterative and recursive GCD, Bézout coefficients and modular inverse. Validate inputs and verify invariants rather than relying on a printed answer alone.
Matrix operations
A matrix product exists when the first matrix’s column count equals the second matrix’s row count. Compute ordinary products first and reduce entries modulo m. For a 2×2 matrix, the determinant and adjugate determine the inverse when its determinant is a unit.
Program verification
Use an alphabet of 27 distinct symbols for the Hill program. Encode digraphs as column vectors, declare a deterministic padding rule, and verify K \(K^{-1}\) ≡ I. Inspect actual execution frames in Python Visualizer and compare loop and recursive implementations on the same inputs.
Prerequisites: EC05 and earlier foundations as applicable.
Algorithm structure and data flow. Use the simulation to inspect the corresponding numerical transformations.
Engineering diagrams
Linear algebra over a modular ring.
Scientific foundations and worked examples
Mathematical contracts before coding
A factorization is a multiset of primes whose product equals the input. Euler totient counts coprime residues; gcd is nonnegative, and gcd(a,0)=|a|. Recursive Euclid terminates because the nonnegative remainder decreases. Modular inverse is defined only for coprime operands. Verify the returned Bézout coefficients using the original input values, not the final remainders.
Matrix multiplication and reversible Hill keys
For a 2×2 matrix K=[[a,b],[c,d]], det K=ad−bc. A modular inverse exists when gcd(det K,m)=1. The adjugate is [[d,−b],[−c,a]], and multiplication by det(K)⁻¹ modulo m gives the inverse. Matrix multiplication combines rows with columns; test K \(K^{-1}\)=I modulo m and round-trip an encoded message. A unit determinant modulo m is necessary even when the real-valued inverse exists.
Engineering principles · additional worked teaching example
Reusable modular code should normalize residues and reject noninvertible operands. Python pow(a,-1,m) raises ValueError when gcd≠1; for pow(3,-1,7) result5 as 3×5≡1. Keep manual EEA trace when the algorithm itself is the learning target.
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
For Python and positive n, a%n gives the canonical residue. pow(a,e,n) computes modular exponentiation without constructing a huge integer. An inverse exists exactly when gcd(a,n)=1.
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
Bézout identity and modular inverse
The Euclidean divisions produce the gcd. Back-substitution yields integer coefficients x,y; x reduced modulo n gives the inverse if the gcd is one.
For 7 and 11: 11=7+4, 7=4+3, 4=3+1; 1=2(11)−3(7), so \(7^{-1}\)≡8 modulo 11.
Concept animation · operation pathway
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 · Input
Input
Input
3, exponent 4, modulus 7
Square
Input
3, exponent 4, modulus 7
Square
\(3^{2}\) mod 7=2
Square again
Input
3, exponent 4, modulus 7
Square
\(3^{2}\) mod 7=2
Square again
\(2^{2}\) mod 7=4
Return
Input
3, exponent 4, modulus 7
Square
\(3^{2}\) mod 7=2
Square again
\(2^{2}\) mod 7=4
Return
pow(3,4,7)=4
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 explanationsWhy use integer arithmetic?
It preserves exact modular calculations.
What is a recursion base case?
A terminating condition.
Why check matrix determinant?
It determines invertibility modulo m.
How validate GCD code?
Compare against known results and math.gcd.
What is prime factorization?
Writing a positive integer as a product of prime powers.
What is the base case of recursive Euclid?
When b=0, return abs(a).
What is gcd(252,105)?
21.
What is φ(12)?
4.
What does a negative determinant require before modular inversion?
Reduce it modulo the modulus and test coprimality.
Why record function inputs in a Python trace?
To explain intermediate state and reproduce results.
What should a singular Hill key cause?
A clear error or rejection, not a fabricated inverse.
What does matrix multiplication order affect?
The resulting entries; matrix multiplication is generally not commutative.
Why use assert for reference cases?
To detect disagreement with the expected result automatically.
What should a local trace show for recursion?
Successive frames and return values until the base case.
A recursive gcd function reaches b=0. What should it return?
Return |a| for a nonnegative gcd. This is the base case.
How can you verify a computed modular inverse in Python?
Check (a*inv) % n == 1, after verifying gcd(a,n)==1.
Why compare the trace with an independent Hill matrix calculation?
It reveals incorrect modulus, vector orientation, matrix multiplication or inverse implementation.
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 · Factorization and totient
Factor 24 and derive φ(24) by hand. Explain the definition of primeFactors and eulerTotient.
Engineering method — Reusable modular code should normalize residues and reject noninvertible operands. Python pow(a,-1,m) raises ValueError when gcd≠1; for pow(3,-1,7) result5 as 3×5≡1. Keep manual EEA trace when the algorithm itself is the learning target. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
02 · GCD and inverse
Trace iterative and recursive gcd(121,55), extended gcd(9,7) and inverse of 8 modulo 27. Record a case where an inverse does not exist.
Engineering method — Reusable modular code should normalize residues and reject noninvertible operands. Python pow(a,-1,m) raises ValueError when gcd≠1; for pow(3,-1,7) result5 as 3×5≡1. Keep manual EEA trace when the algorithm itself is the learning target. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
03 · Matrices
Compute det([[2,0],[2,4]]). Multiply A=[[1,2,3],[4,5,6]] by B=[[1],[2],[3]], then reduce the product mod 7. Show dimension checks.
Engineering method — Reusable modular code should normalize residues and reject noninvertible operands. Python pow(a,-1,m) raises ValueError when gcd≠1; for pow(3,-1,7) result5 as 3×5≡1. Keep manual EEA trace when the algorithm itself is the learning target. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
04 · Hill functions
State the mathematical preconditions of Hill encryption/decryption, then calculate one assigned block manually before implementing and testing the functions.
Engineering method — Reusable modular code should normalize residues and reject noninvertible operands. Python pow(a,-1,m) raises ValueError when gcd≠1; for pow(3,-1,7) result5 as 3×5≡1. Keep manual EEA trace when the algorithm itself is the learning target. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
05 · Code design
Code design · Independent work
Describe a test suite for inverse(a,m) using (4,9), (6,9), and (−2,9). Calculate expected outcomes.
Code design — Reusable modular code should normalize residues and reject noninvertible operands. Python pow(a,-1,m) raises ValueError when gcd≠1; for pow(3,-1,7) result5 as 3×5≡1. Keep manual EEA trace when the algorithm itself is the learning target. 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 · EC06-01
Predict print(-17%5, 17//5, pow(3,4,7)).
Intermediate · Calculate or trace
Independent theoretical exercise · EC06-02
Find pow(7,-1,19) manually.
Intermediate · Interpret the result
Independent theoretical exercise · EC06-03
What happens with pow(6,-1,15)?
Advanced · Analyze a condition
Independent theoretical exercise · EC06-04
Give reusable guard for modulus n and inverse.
Advanced · Diagnose or compare
Independent theoretical exercise · EC06-05
For repeated squaring 5^13 mod 11, show residues 5^1,5^2,5^4,5^8 and combine.
Challenging · Engineering verification
Independent theoretical exercise · EC06-06
A student computes (a+b)%0; diagnose.
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.
Compare observations with the reference checks and submit the required evidence.
Analytical preparation — before Python
Complete this written or hand-calculation activity first, then compare it with the simulator and executable implementation.
State the mathematical contract and test cases for each function. Calculate a Hill determinant, inverse and matrix product independently of Python.
Evidence: show the derivation, intermediate values and independent checks; explain any mismatch with the practical result.
Practical laboratory manual
Scientific experimental protocol
Research question: Do independently implemented modular and matrix algorithms agree?
Independent variables
Input integers, matrices, modulus
Dependent observations
GCD, coefficients, inverse, products, recovered text
Controls
Use the same inputs for recursion and iteration; check dimensions and inverse conditions.
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)
GCD
121,55
11 for both implementations
Enter observation
Matrix product
[[1,2,3],[4,5,6]] × [[1],[2],[3]]
[[14],[32]]
Enter observation
Modular inverse
[[2,0],[2,4]], modulus 27
A × \(A^{-1}\) mod 27 equals identity
Enter observation
Analysis: Record function-level test inputs and outputs; explain any invalid dimensions or non-invertible matrix rather than skipping failures.
Implement and test modular-arithmetic helpers that can be reused in RSA and Hill cipher laboratories.
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 lab06.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
Factorization, totient and GCD functions
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.
Implement myGCDIter and myGCDRec; test 121,55 . Use Python Visualizer to compare loop and recursion.
Implement extendedGCD(a,b); test 9,7 and verify sa+tb=gcd.
Evidence to record
Function test table and recursion trace.
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
Modular inverse and matrix utilities
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.
Implement inverseMod(a,m), test 8,27 and a nonunit; implement det for [[2,0],[2,4]].
Implement matrixMult with dimension validation; test A=[[1,2,3],[4,5,6]], B=[[1],[2],[3]].
Implement matrixMultMod(A,B,7), then test incompatible dimensions.
Evidence to record
Actual results, error control and modular products.
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
Hill Python 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.
Implement hillCipherEncrypt, inverseMatrixMod and hillCipherDecrypt using the preceding functions. Use alphabet "ABCDEFGHIJKLMNOPQRSTUVWXYZ " (27 symbols), key [[2,0],[2,4]] and HILLS; state your padding convention.
Validate A×\(A^{-1}\)≡I mod 27 and round-trip the padded input. Reject keys whose determinant has no modular inverse.
Decrypt the exact assigned ciphertext below with the key/alphabet, then re-encrypt the candidate.
Experimental inputs and checks
Challenge ciphertext
GIZNBAZEHXK HDJJ LZKNLI ZAHDM IY WOTWMJF
Evidence to record
Python code, matrix inverse check and challenge recovery.
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.
Verification criteria
primeFactors(24)=[2,2,2,3]; φ(24)=8; gcd(121,55)=11; the modular matrix inverse gives the identity.
Deliverables
Submit the named functions and unit tests covering correct results, incompatible dimensions, noninvertible keys and round trips.
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
# EC06 · Modular arithmetic in Python — Reusable crypto functions
**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
Implement and test modular-arithmetic helpers that can be reused in RSA and Hill cipher laboratories.
**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. Factorization, totient and GCD functions — complete its numbered steps and record the requested evidence.
3. Modular inverse and matrix utilities — complete its numbered steps and record the requested evidence.
4. Hill Python implementation — complete its numbered steps and record the requested evidence.
5. Compare observations with the reference checks and submit the required evidence.
**Evidence:** primeFactors(24)=[2,2,2,3]; φ(24)=8; gcd(121,55)=11; the modular matrix inverse gives the identity.
**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. Factorization, totient and GCD functions — complete its numbered steps and record the requested evidence.
3. Modular inverse and matrix utilities — complete its numbered steps and record the requested evidence.
4. Hill Python implementation — 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
# =====================================================================
# EC06 | Code cell 01 | Modular arithmetic in Python — Reusable crypto functions
# 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)
# =====================================================================
# EC06 | Code cell 02 | Modular arithmetic in Python — Reusable crypto functions
# 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
# =====================================================================
# EC06 | Code cell 03 | Modular arithmetic in Python — Reusable crypto functions
# 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]]
# =====================================================================
# EC06 | Code cell 04 | Modular arithmetic in Python — Reusable crypto functions
# 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)
# =====================================================================
# EC06 | Code cell 05 | Modular arithmetic in Python — Reusable crypto functions
# 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
# =====================================================================
# EC06 | Code cell 06 | Modular arithmetic in Python — Reusable crypto functions
# 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 06 — reusable modular arithmetic and matrix functions."""
from lab04 import primeFactors,eulerTotient,extendedGCD,inverseMod,inverseMatrixMod,hill
# Define the reusable operation myGCDIter; keep its logic separate from the trial.
def myGCDIter(a,b):
while b: a,b=b,a%b
return abs(a)
### Implementation cell 2
Inspect the definitions, then execute to make them available for the investigation.
18Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC06 | Code cell 07 | Modular arithmetic in Python — Reusable crypto functions
# Purpose: Implementation cell 2 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.
# =====================================================================
# Define the reusable operation myGCDRec; keep its logic separate from the trial.
def myGCDRec(a,b): return myGCDRec(b,a%b) if b else abs(a)
# Define the reusable operation det; keep its logic separate from the trial.
def det(a):
if len(a)!=2 or any(len(r)!=2 for r in a): raise ValueError('Expected 2x2 matrix')
return a[0][0]*a[1][1]-a[0][1]*a[1][0]
# Define the reusable operation matrixMult; keep its logic separate from the trial.
def matrixMult(a,b):
if not a or not b or not a[0] or not b[0] or any(len(r)!=len(a[0]) for r in a) or any(len(r)!=len(b[0]) for r in b) or len(a[0])!=len(b):
raise ValueError('Incompatible matrix dimensions')
return [[sum(x*y for x,y in zip(row,col)) for col in zip(*b)] for row in a]
### Implementation cell 3
Inspect the definitions, then execute to make them available for the investigation.
20Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC06 | Code cell 08 | Modular arithmetic in Python — Reusable crypto functions
# Purpose: Implementation cell 3 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.
# =====================================================================
# Define the reusable operation matrixMultMod; keep its logic separate from the trial.
def matrixMultMod(a,b,m):
if m<2: raise ValueError('Modulus must exceed one')
return [[x%m for x in row] for row in matrixMult(a,b)]
# Define the reusable operation hillCipherEncrypt; keep its logic separate from the trial.
def hillCipherEncrypt(pt,k,alphabet): return hill(pt,k,alphabet)
# Define the reusable operation hillCipherDecrypt; keep its logic separate from the trial.
def hillCipherDecrypt(ct,k,alphabet): return hill(ct,k,alphabet,True)
## 4. Execute reference controls
The program checks selected algorithm outcomes. Record the observed output. These checks do not replace the independent calculation assignment.
22Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC06 | Code cell 09 | Modular arithmetic in Python — Reusable crypto functions
# 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.
# =====================================================================
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert primeFactors(24) == [2, 2, 2, 3] and eulerTotient(24) == 8
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert myGCDRec(121, 55) == myGCDIter(121, 55) == 11
# Set (g, s, t) for the next computation or reference condition.
g, s, t = extendedGCD(9, 7)
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert 9 * s + 7 * t == g == 1
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert inverseMod(8, 27) == 17
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert matrixMult([[1, 2, 3], [4, 5, 6]], [[1], [2], [3]]) == [[14], [32]]
# Set k for the next computation or reference condition.
k = [[2, 0], [2, 4]]
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert matrixMultMod(k, inverseMatrixMod(k, 27), 27) == [[1, 0], [0, 1]]
# Set a for the next computation or reference condition.
a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ '
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert hillCipherDecrypt(hillCipherEncrypt('HILLS', k, a), k, a) == 'HILLSX'
print('All helper and matrix round-trip tests passed')
## 5. Controlled variation
Predict the effect of the parameter changes below. Compare each actual result to your prediction.
24Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC06 | Code cell 10 | Modular arithmetic in Python — Reusable crypto functions
# 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 a,b in ((252,105),(67,31)):
print(a,b,extendedGCD(a,b))
## 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.)
26Instructions · 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. Factorization, totient and GCD functions — 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 recursive Euclid equivalent to the iterative form?
When is a matrix multiplication undefined?
What is the role of a determinant inverse in Hill decryption?
Submission: Submit the named functions and unit tests covering correct results, incompatible dimensions, noninvertible keys and round trips.
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