Skip to main content
IoT
PSUT Engineering StudioPrincess Sumaya University for Technology
V21.6.5 · Student / connected
Cyber Defense StudioIoT Security and PrivacyExperimentsWorkspaces
Home / IoT Security and Privacy / EC06
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
ESSENTIAL LABORATORY · EC06 · IoT SECURITY AND PRIVACY
IoT Security and Privacy

Modular arithmetic in Python — Reusable crypto functions

Implement and test modular-arithmetic helpers that can be reused in RSA and Hill cipher laboratories.

Design experiment & verify evidence →
EC06 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
EC06 · Academic orientation

Scope and objectives

Scope of the experiment

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.

  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.

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.

TrialChanged settingFixed settingsPredicted resultActual observation / unitsEvidence / uncertainty
A: baselineReferenceRecordPredictRecordRecord
B: one changeRecordSame as APredictRecordRecord
A: repeatRestoreSame as APredictRecordRecord

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 concepts and engineering principles

Scientific architecture · EC06 · Modular arithmetic in Python — Reusable crypto functions

Recursive GCD and modular arithmetic — gcd(252,105) / 252 mod 105=42; gcd(105,42) / remainder 21; gcd(42,21) / remainder 0; gcd(21,0) / return 21; Unwind / use result in modular operations
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.

EC06 engineering diagram
Algorithm structure and data flow. Use the simulation to inspect the corresponding numerical transformations.

Engineering diagrams

Linear algebra over a modular ring.
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.

\[\gcd(a,n)=ax+ny,\qquad ax\equiv1\pmod n\quad\text{when }\gcd(a,n)=1\]

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.

Modular arithmetic in Python — Reusable crypto functions: operation pathwayInput3, exponent 4,modulus 7Square3² mod 7=2Square again2² mod 7=4Returnpow(3,4,7)=4Read the active operation, then inspect the accumulated state.

Step 1 of 4 · Input

Input

Input
3, exponent 4, modulus 7

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 explanations
Why 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.

Shared research workbenches · network designer & advanced studies
Concurrent-device simulation & Monte Carlo research
Distributed digital twin · topology, protocol & battery research