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 · CR40 · NUMBER THEORY
IoT Security and Privacy

Fermat and Euler theorems

Fermat: for prime p and a not divisible by p, a^(p−1)≡1.

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

Scope and objectives

Scope of the experiment

Euler's totient φ(n) counts residues from 1 to n−1 coprime to n (for n>1). Multiplication by a unit permutes the units, leading to Euler's theorem.

The focus of this experiment is to state assumptions of Fermat and Euler theorems. Students then reduce modular powers using the appropriate exponent property, and verify residues and identify invalid noncoprime use. 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

  • State assumptions of Fermat and Euler theorems.
  • Reduce modular powers using the appropriate exponent property.
  • Verify residues and identify invalid noncoprime use.
  • 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 state assumptions of Fermat and Euler theorems, reduce modular powers using the appropriate exponent property, and verify residues and identify invalid noncoprime use.

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 residues and identify invalid noncoprime use. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to Repeated squaring and operation counts.

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

CR40 · Fermat and Euler theorems

Euler’s totient φ(n) counts residues 1…n−1 coprime to n. Euler’s theorem applies when gcd(a,n)=1. Fermat’s little theorem is its prime-modulus case, φ(p)=p−1. For distinct primes p,q, φ(pq)=(p−1)(q−1).

Learning objectives

Trace the named operation, reproduce intermediate values, verify the result and explain the consequences of a controlled change.

Prerequisites

Before starting

Environment: standard computer, browser and Python/WSL.

Simulation: Live browser calculation within the displayed input bounds.

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

Euler’s totient φ(n) counts residues 1…n−1 coprime to n. Euler’s theorem applies when gcd(a,n)=1. Fermat’s little theorem is its prime-modulus case, φ(p)=p−1. For distinct primes p,q, φ(pq)=(p−1)(q−1).

Learning objectives

Trace the named operation, reproduce intermediate values, verify the result and explain the consequences of a controlled change.

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 browser calculation within the displayed input bounds.

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

Mathematical model

gcd(a,n)=1 ⇒ a^φ(n)≡1 (mod n)

Worked calculation

φ(17)=16; φ(55)=40. 3^16 mod 17=1. For a=5,n=55 the coprimality hypothesis fails.

Common error and troubleshooting

If a result is not 1 when the hypothesis fails, this does not refute Euler’s theorem.

Check the input format and trace the first step at which your manual result differs. Compare with Python before drawing a conclusion.

Fermat and Euler

1 · Principles and purpose

Euler's totient φ(n) counts residues from 1 to n−1 coprime to n (for n>1). Multiplication by a unit permutes the units, leading to Euler's theorem.

2 · Mathematical and algorithmic foundations

If gcd(a,n)=1 then a^φ(n)≡1 (mod n). For prime p, φ(p)=p−1. For distinct primes p,q, φ(pq)=(p−1)(q−1).

3 · Worked teaching example

For n=10, units are 1,3,7,9, so φ=4. \(3^{4}\)=81≡1; \(2^{4}\)=16≡6 because gcd(2,10)≠1. The condition is essential.

Verified default trace · 6 intermediate states

Given parameters (teaching example):

{
  "a": 3,
  "n": 17
}
StageComputed values
1{ "units": [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ], "phi": 16, "gcd": 1 }
2{ "bit_index": 0, "selected": 0, "power_residue": 3, "accumulator_before": 1, "accumulator": 1, "next_square": 9 }
3{ "bit_index": 1, "selected": 0, "power_residue": 9, "accumulator_before": 1, "accumulator": 1, "next_square": 13 }
4{ "bit_index": 2, "selected": 0, "power_residue": 13, "accumulator_before": 1, "accumulator": 1, "next_square": 16 }
5{ "bit_index": 3, "selected": 0, "power_residue": 16, "accumulator_before": 1, "accumulator": 1, "next_square": 1 }
6{ "bit_index": 4, "selected": 1, "power_residue": 1, "accumulator_before": 1, "accumulator": 1, "next_square": 1 }

Recorded result

{
  "phi": 16,
  "residue": 1,
  "condition": true,
  "fermat_applies": true
}

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

Euler and Fermat

The product ranges over distinct prime factors. For a prime modulus p, phi(p)=p−1. The coprimality condition is essential.

\[\varphi(n)=n\prod_{p\mid n}\left(1-\frac1p\right),\qquad a^{\varphi(n)}\equiv1\pmod n\quad(\gcd(a,n)=1)\]

Concept animation · Euler unit residues

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.

Classify residues1234567891011121314151617181920Select units1234567891011121314151617181920Multiply by a unit12345678910111213141516171819202 × units mod 212481016201511131719Verify theorem12345678910111213141516171819202 × units mod 212481016201511131719

Step 1 of 4 · Classify residues

Classify residues

Modulo 21, a unit is a residue coprime to 21.

Teaching example only; inspect live calculations or real practical evidence separately.

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

03 · Interactive simulation

Baseline diagram loaded. Interactive engine initializing…

Verified baseline reference — use the live workstation below to explore steps and compare inputs.
CR40 calculated step 1Totient: highlight the residues coprime to n12345678910111213141516φ(17) = 16 · gcd(a,n) = 1

Enter integer values or choose a worked example. Recompute runs the mathematical algorithm in your browser. Inspect the active SVG state, step backward or forward, and export the trace for comparison with Python.

Calculated result

{
  "phi": 16,
  "residue": 1,
  "condition": true,
  "fermat_applies": true
}
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

Euler’s totient φ(n) counts residues 1…n−1 coprime to n. Euler’s theorem applies when gcd(a,n)=1. Fermat’s little theorem is its prime-modulus case, φ(p)=p−1. For distinct primes p,q, φ(pq)=(p−1)(q−1). gcd(a,n)=1 ⇒ a^φ(n)≡1 (mod n). φ(17)=16; φ(55)=40. 3^16 mod 17=1. For a=5,n=55 the coprimality hypothesis fails. If a result is not 1 when the hypothesis fails, this does not refute Euler’s theorem.

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

List the residues relatively prime to 15, derive φ(15), and verify Euler’s theorem for a=2. Compare with a=3 and explain why the coprimality assumption is essential.

02 · Theorem application

Theorem application · Independent work

List units modulo10 and use Euler's theorem to verify \(3^{4}\) mod10. Why cannot theorem be applied directly to 2?

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

For the separate teaching-test configuration a: 5; n: 55, 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 · CR40-02

A teaching trace for Fermat and Euler theorems contains bit_index: 0; selected: 0; power_residue: 3; accumulator_before: 1; accumulator: 1. Explain the role of next_square (recorded value 9) 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 · CR40-03

The first teaching trace contains units: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; phi: 16; gcd: 1; the last contains bit_index: 4; selected: 1; power_residue: 1; accumulator_before: 1; accumulator: 1; next_square: 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 · CR40-04

Plan a comparison of a: 3; n: 17 with a: 5; n: 55. Record the dependent value phi, identify the changed factor(s), and describe the verification and failure criterion without claiming a real security measurement.

Part B · Guided simulation and practical procedure

Before starting — tools and setup

Standard computer; extract the WSL toolkit into a new directory. For the browser activity, use the integrated workstation. Editable browser calculation

Install Python dependencies only if required by the selected toolkit README. Use its requirements file and virtual environment instructions.

Open complete, verified WSL commands in Part C ↓

01

Baseline calculation or protocol trace

  1. Use the exact baseline input below and write a prediction.
  2. Select the baseline configuration below. Predict the relevant operation using the theory; execute the workstation and record the first and final state. Reproduce the same input with Python.
  3. Save the trace and compare it with the reference output.

Experimental inputs

Experimental reference · json
{"a":3,"n":17}
Verified baseline reference (check after predicting)
Experimental reference · json
{"phi":16,"residue":1,"condition":true,"fermat_applies":true}

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

Record the named intermediate values and final outputs from the selected trace.

Run baseline →
02

Part D · Controlled investigation

  1. Run a=3,n=17 and count highlighted units. Change n to 55 while holding a=3; verify φ(55). Then change a to 5 and explain the failed hypothesis using gcd. Record φ, gcd, and final residue.
  2. Record the conditions held fixed: Keep all inputs other than the stated comparison parameter unchanged; where the task compares protocol configurations, document every changed field.
  3. Collect Record the named intermediate values and final outputs from the selected trace. Compare the first differing intermediate step and explain the relationship.
TrialInput configurationPredictionObservedVerification
1{"a":3,"n":17}
2{"a":5,"n":55}
3{"a":2,"n":55}

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. Reproduce at least one changed input; compare the intermediate values with the browser where supported.
  3. Complete the independent assessment below without copying the worked baseline. Explain discrepancies and distinguish mathematical results from security claims.
Additional investigation instructions
  1. Predict the result using the mathematical model before operating the simulator.
  2. Run a=3,n=17 and count highlighted units. Change n to 55 while holding a=3; verify φ(55). Then change a to 5 and explain the failed hypothesis using gcd. Record φ, gcd, and final residue.
  3. Export the calculated trace. Reproduce the same inputs in Python and compare every relevant intermediate value.
  4. Submit a table with one row per trial: inputs, fixed conditions, intermediate values, measured result, verification equation and interpretation. State why small classroom calculations do not establish production security.
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 CR40
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 CR40/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": {
    "units": [
      1,
      2,
      3,
      4,
      5,
      6,
      7,
      8,
      9,
      10,
      11,
      12,
      13,
      14,
      15,
      16
    ],
    "phi": 16,
    "gcd": 1
  },
  "result": {
    "phi": 16,
    "residue": 1,
    "condition": true,
    "fermat_applies": true
  }
}

Test script output:
CR40 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 | CR40
# Experiment: fermat and euler theorems
# Purpose: expose algorithm states and verify the experiment invariant.
# ------------------------------------------------------------
# CR40 | Fermat and Euler theorems
# Execute the named operation; expose states and assert the laboratory invariant.
import math
import json

def exptrace(a,e,m):
    # Right-to-left square-and-multiply; reduce after every product.
    if e<0 or m<2: raise ValueError('Require nonnegative exponent and modulus >= 2')
    r=1; b=a%m; steps=[]; i=0
    while e:
        bit=e&1; old=r
        if bit: r=r*b%m
        steps.append({'bit_index':i,'selected':bit,'power_residue':b,'accumulator_before':old,'accumulator':r,'next_square':b*b%m}); b=b*b%m; e//=2; i+=1
    return r,steps

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

DEFAULT={'a': 3, 'n': 17}
ALTERNATE={'a': 5, 'n': 55}

def run(overrides=None):
    # Merge only explicitly supplied inputs with the lecture baseline.
    params={**DEFAULT, **(overrides or {})}
    a=params['a']
    n=params['n']
    units=[i for i in range(1,n) if math.gcd(i,n)==1]; phi=len(units)
    y,trace=exptrace(a,phi,n);steps=[{'units':units,'phi':phi,'gcd':math.gcd(a,n)}]+trace
    result={'phi':phi,'residue':y,'condition':math.gcd(a,n)==1,'fermat_applies':prime(n) and a%n!=0}
    # Independently check the stated mathematical or protocol invariant.
    assert not result["condition"] or result["residue"]==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
{
  "phi": 16,
  "residue": 1,
  "condition": true,
  "fermat_applies": true
}

05 · Interactive flashcards

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

Browse all explanations
What does φ(n) count?

Residues coprime to n.

What is φ(55)?

40.

When is Fermat’s little theorem applicable?

Prime p with a not divisible by p.

Why is a=5,n=55 a poor test of Euler’s theorem?

gcd(5,55)=5, so its hypothesis fails.

Explain the baseline worked calculation.

φ(17)=16; φ(55)=40. 3^16 mod 17=1. For a=5,n=55 the coprimality hypothesis fails.

What is the common misconception?

If a result is not 1 when the hypothesis fails, this does not refute Euler’s theorem.

06 · Knowledge assessment

Formative check

When does Euler’s theorem guarantee a^φ(n)≡1?

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

Independent assessment

For n=21, enumerate units and test Euler’s theorem using a=2 and a=3.

Submit handwritten or typed calculations, a browser trace and matching Python output. Explain the operation and any invalid condition. Evaluation: mathematics 40%, reproducibility 30%, interpretation 20%, limitations 10%.

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