IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
CRYPTOGRAPHY ENGINEERING · CR49 · KEY AGREEMENT
IoT Security and Privacy
Diffie–Hellman key agreement
Establish the same secret with two modular powers.
CR49 · Laboratory mentorAsk about the current operation and its intermediate values.
CR49 · Academic orientation
Scope and objectives
Scope of the experiment
Both parties publish values derived from secret exponents in a common group. The equal shared secret follows from commutativity of exponent multiplication; the exchange alone does not establish identity.
The focus of this experiment is to calculate public Diffie–Hellman values from classroom exponents. Students then derive the shared secret independently at both peers, and explain why agreement alone does not authenticate identities. 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
Calculate public Diffie–Hellman values from classroom exponents.
Derive the shared secret independently at both peers.
Explain why agreement alone does not authenticate identities.
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 calculate public Diffie–Hellman values from classroom exponents, derive the shared secret independently at both peers, and explain why agreement alone does not authenticate identities.
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 why agreement alone does not authenticate identities. Separate predicted values from observations.
Prerequisite knowledge and related learning
Review the following catalogue prerequisites before starting. After completion, continue to Authenticated key agreement: trust decision.
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
CR49 · Diffie–Hellman key agreement
For public prime q and generator g, Alice sends A=gˣᵃ mod q and Bob B=gˣᵇ mod q. Both compute g^(xa·xb) mod q independently. Private exponents stay local; DH alone does not authenticate peers or directly encrypt messages.
Learning objectives
Establish the same secret with two modular powers. Predict a result, inspect intermediate states, verify the invariant and explain the specified boundary case.
Complete the six stages in order. Use the same experiment inputs when comparing manual, browser and Python results.
02 · Concepts and mathematical foundations
For public prime q and generator g, Alice sends A=gˣᵃ mod q and Bob B=gˣᵇ mod q. Both compute g^(xa·xb) mod q independently. Private exponents stay local; DH alone does not authenticate peers or directly encrypt messages.
Learning objectives
Establish the same secret with two modular powers. Predict a result, inspect intermediate states, verify the invariant and explain the specified boundary case.
Mathematical verification and controlled comparison
Substitute the output into its defining equation or check the protocol invariant. A controlled comparison changes one input while holding others fixed. Cite actual trace values and identify the limitations of the evidence.
Before starting
Environment: standard computer, browser and Python/WSL.
Simulation: live bounded classroom calculations in the browser and Python.
Technical scope: Small synthetic parameters; educational mathematics, not production cryptography.
Diffie–Hellman key agreement
1 · Principles and purpose
Both parties publish values derived from secret exponents in a common group. The equal shared secret follows from commutativity of exponent multiplication; the exchange alone does not establish identity.
2 · Mathematical and algorithmic foundations
A=gᵃ mod p,B=gᵇ mod p; S=Bᵃ=Aᵇ=g^(ab) mod p. For p=23,g=5,a=6,b=15, A=8,B=19.
3 · Worked teaching example
\(19^{6}\) mod23=2 and \(8^{15}\) mod23=2. Public values may be observed; private exponents and shared secret are not transmitted. Derive application keys with a KDF and authenticate the peers.
Verified default trace · 4 intermediate states
Given parameters (teaching example):
{
"q": 23,
"g": 5,
"xa": 6,
"xb": 15
}
Stage
Computed values
1
{
"actor": "Alice",
"public": 8
}
2
{
"actor": "Bob",
"public": 19
}
3
{
"actor": "Alice",
"received": 19,
"shared": 2
}
4
{
"actor": "Bob",
"received": 8,
"shared": 2
}
Recorded result
{
"A": 8,
"B": 19,
"shared": 2,
"match": 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
Diffie–Hellman agreement
p and g are public domain parameters; a,b are private exponents. Equal shared values do not establish peer identity without authenticated key agreement.
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 · Local secrets
Local secrets
Teaching field p=29, base g=2. Alice chooses 5, Bob 9; never transmit these.
Public values
Alice computes A=3; Bob computes B=19.
Exchange
Only A=3, B=19 and public parameters cross the channel.
Shared secret
Alice computes 19^5 mod 29=21; Bob computes 3^9 mod 29=21. Unauthenticated DH alone does not establish identity.
Teaching example only; inspect live calculations or real practical evidence separately.
Shared research workbenches · network designer & advanced studiesConcurrent-device simulation & Monte Carlo research
Reference SVG (visible without scripts). Use the editable workstation below to calculate or run the experiment.
Choose a reference trial or edit the parameters. The workstation computes new results; practical cryptography uses Web Crypto when available and labels recorded Python references separately.
Verified baseline reference
Calculated result or labeled reference
{
"A": 8,
"B": 19,
"shared": 2,
"match": true
}
Complete trace
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.
q=23,g=5,xa=6,xb=15 gives A=8, B=19, \(B^{6}\) mod 23=2 and \(A^{15}\) mod 23=2.
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
Using q=23 and α=5, choose Alice private value 4 and Bob private value 7. Compute both public values and both shared secrets with modular exponentiation. Identify which values travel over the public channel.
Application and derivation — A=gᵃ mod p,B=gᵇ mod p; S=Bᵃ=Aᵇ=g^(ab) mod p. For p=23,g=5,a=6,b=15, A=8,B=19. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
02 · DH calculation
DH calculation · Independent work
For p=23,g=5,a=2,b=3, compute public values and shared secret both ways.
DH calculation — Review the defining equations and compare the input restrictions and state transitions in Concepts. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
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 · CR49-01
For the separate teaching-test configuration q: 23; g: 5; xa: 6; xb: 7, predict A 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 · CR49-02
A teaching trace for Diffie–Hellman key agreement contains actor: Bob; public: 19. Explain the role of public (recorded value 19) 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 · CR49-03
The first teaching trace contains actor: Alice; public: 8; the last contains actor: Bob; received: 8; shared: 2. 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 · CR49-04
Plan a comparison of q: 23; g: 5; xa: 6; xb: 15 with q: 23; g: 5; xa: 6; xb: 7. Record the dependent value B, identify the changed factor(s), and describe the verification and failure criterion without claiming a real security measurement.
Part B · Guided simulation and practical procedure
Before starting — tools and setup
Standard computer; run the integrated workstation or extracted toolkit. All classroom calculations run locally.
Install Python dependencies only if required by the selected toolkit README. Use its requirements file and virtual environment instructions.
Predict public values; trace both parties, verify matching secrets without transmitting private values.
Export the trace and compare the result with the reference.
Experimental inputs
Experimental reference · json
{"q":23,"g":5,"xa":6,"xb":15}
Verified baseline reference (check after predicting)
Experimental reference · json
{"A":8,"B":19,"shared":2,"match":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
Public parameters, classroom private values, A/B, both derived secrets and match decision.
Part E/F · Independent Python verification and deliverables
Download the notebook or toolkit and run the default example.
Use python3 lab.py --inputs followed by the JSON from a trial. Compare exact math; for randomized or timed experiments compare invariants and report actual measurements separately.
Complete the independent assessment below without copying the worked baseline. Explain discrepancies and distinguish mathematical results from security claims.
Additional investigation instructions
Read the theory and prerequisite labs. Run the baseline and record the input and result.
Verify the reference result A=8,B=19,K=2. Change Bob’s private value to 7; check matching shared values.
Locate the first intermediate step where the two cases differ. Verify the defining equation or decision rule.
Submit a two-row comparison table, trace evidence and a conclusion with limitations.
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).
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 CR49
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.
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 CR49/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.
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 | CR49
# Experiment: diffie hellman lecture key agreement
# Purpose: expose algorithm states and verify the experiment invariant.
# ------------------------------------------------------------
# CR49 | Diffie–Hellman lecture key agreement
# Execute the named operation; expose states and assert the laboratory invariant.
import json
DEFAULT={'q': 23, 'g': 5, 'xa': 6, 'xb': 15}
ALTERNATE={'xb': 7}
def run(overrides=None):
# Merge only explicitly supplied inputs with the reference baseline.
params={**DEFAULT, **(overrides or {})}
q=params['q']
g=params['g']
xa=params['xa']
xb=params['xb']
if not (all(type(x) is int for x in (q,g,xa,xb)) and 5<=q<=997 and all(q%i for i in range(2,int(q**0.5)+1)) and 2<=g<q and 1<=xa<=q-2 and 1<=xb<=q-2 and len({pow(g,i,q) for i in range(q-1)})==q-1): raise ValueError('Invalid prime, generator or private exponent')
A=pow(g,xa,q);B=pow(g,xb,q);ka=pow(B,xa,q);kb=pow(A,xb,q)
steps=[{'actor':'Alice','public':A},{'actor':'Bob','public':B},{'actor':'Alice','received':B,'shared':ka},{'actor':'Bob','received':A,'shared':kb}];result={'A':A,'B':B,'shared':ka,'match':ka==kb}
# Independently check the stated mathematical or protocol invariant.
assert result["match"], "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
{
"A": 8,
"B": 19,
"shared": 2,
"match": true
}
05 · Interactive flashcards
Recall before revealing. Review and mastery ratings remain on this device.
Browse all explanationsWhat crosses the channel?
Public A and B.
Reference secret?
2.
Why use a KDF?
Derive context-specific traffic keys.
What does unauthenticated DH establish?
Common secret, not identity
What evidence should be recorded?
Public parameters, classroom private values, A/B, both derived secrets and match decision.
How should the comparison be controlled?
Change only xb to 7 then 9. Keep q,g,xa fixed. Compare public values and shared-secret equality.
06 · Knowledge assessment
Change only xb to 7 then 9. Keep q,g,xa fixed. Compare public values and shared-secret equality. Submit the stated measurements, a reasoned comparison and independent verification. Criteria: mathematical correctness 40%, reproducibility 30%, interpretation 20%, limitations 10%.
Formative knowledge check
What does unauthenticated DH establish?
Responses are for instructor review; no grading key is provided here.
Part F · Engineering evidence record
Record the baseline, prediction, changed input, observed result, discrepancy and limitation. Save locally or export with the displayed result. This is not an official submission.