Skip to main content
PSUT / IoTEngineering learning studio
WORKSPACE
Offline-first portalDr. Mohammad Alja’afreh
Cyber Defense StudioIoT Security and PrivacyExperimentsWorkspaces
ENGINEERING WORKSPACE
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
KALI WSL / OPTIONAL SECURITY EXTENSION
IoT Security and Privacy

K18 · Comparative AES-GCM and Ascon benchmarking

Ask Dr. Mohammad · K18 →

Measure both implementations under paired host conditions; distinguish implementation overhead from algorithm properties.

← Security range
Design experiment & verify evidence →
K18 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Kali & IoT securityK18 · Comparative AES-GCM and Ascon benchmarking

Before you start

Complete K13, K15. Copy security_extensions.py and ascon_course.py into ~/kali-labs; existing toolkit dependencies are sufficient. Use fictional data, normal user and no external targets.

Learning outcome

Measure both implementations under paired host conditions; distinguish implementation overhead from algorithm properties.

Updated Kali toolkit

Predict: Record the expected outcomes before running the program.

K18 · Academic orientation

Scope and objectives

Scope of the experiment

Measure both implementations under paired host conditions; distinguish implementation overhead from algorithm properties.

The focus of this experiment is to compare AES-GCM and Ascon under identical message and trial conditions. Students then calculate latency and throughput from actual observations, and interpret library and host limitations without extrapolating hardware performance. 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

  • Compare AES-GCM and Ascon under identical message and trial conditions.
  • Calculate latency and throughput from actual observations.
  • Interpret library and host limitations without extrapolating hardware performance.
  • Identify the configured inputs (Payload size (B); Measured trials per algorithm; Warm-up trials per algorithm) and record the corresponding observed outputs with units where applicable.
  • 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 compare AES-GCM and Ascon under identical message and trial conditions, calculate latency and throughput from actual observations, and interpret library and host limitations without extrapolating hardware performance.

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 interpret library and host limitations without extrapolating hardware performance. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to K19 · Certificate revocation lifecycle.

Environment and experimental methodology

The specified isolated laboratory environment, with local synthetic inputs and authorized services only. Use the experiment-specific setup and verification instructions.

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.

Understand the experiment

Scientific architecture · AES-GCM versus Ascon host comparison

AES-GCM versus Ascon benchmarking — Equal payload and AAD / fixed fixture; AES-GCM / encrypt + verify; Ascon-AEAD128 / encrypt + verify; Repeat timer / warm-up and samples; Compare medians / host, not embedded hardware
Scientific concept map: Equal message fixture — Identical sizes; AES-GCM — Authenticated encryption; Ascon-AEAD128 — Authenticated encryption; Host timer — Repeated trials; Comparison — Correctness and latency.

Scientific foundations and analytical reasoning

Comparative benchmarks require matched payloads and independent warm-up. Timing includes language/runtime and implementation costs.

Before operating the equipment or executing the program, derive the expected outcome using the required theoretical work in Experiment. Use the diagram to identify the variables and system boundaries.

Scientific theory · Matched cryptographic comparison

AES-GCM and Ascon-AEAD128 provide authenticated encryption but differ in internal design and platform acceleration. Fair timing compares the same message lengths, repetitions and measurement boundaries, with independent warm-up and correct verification. Include ciphertext and tag overhead separately.

Worked example and engineering interpretation

For a 64-byte message and a 16-byte tag, both outputs contain 80 bytes before nonce/metadata if the configured tag length is 16 bytes. Throughput is payload bytes divided by elapsed time. A faster host implementation does not prove lower MCU energy.

Engineering principles · additional worked teaching example

Fair AES-GCM/Ascon benchmarks use equal payload sizes, repeat counts, host, measurement scope and environment. For paired median times 10 µs and 20 µs, ratio2 is implementation-specific, not universal algorithm superiority.

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.

How to investigate K18 · Comparative AES-GCM and Ascon benchmarking

Measure both implementations under paired host conditions; distinguish implementation overhead from algorithm properties.

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: Measure both implementations under paired host conditions; distinguish implementation overhead from algorithm properties.

  1. Select 128 bytes, 10 measured trials and 3 warm-ups per algorithm. Inspect the per-trial timings and p50/p95; warm-ups are excluded.
  2. Repeat for 32, 512 and 1024 bytes with identical trial counts. Compare size-dependent differences; both ciphertext-plus-tag lengths must be payload+16.
  3. Inspect 12-byte AES-GCM IV and 16-byte Ascon nonce assumptions. Compare bytes if nonce is carried separately.
  4. Repeat each size and discuss measurement variability and implementation differences.

Reference check:

Model boundary:

Independent task and submission evidence

2. Repeat for 32, 512 and 1024 bytes with identical trial counts. Compare size-dependent differences; both ciphertext-plus-tag lengths must be payload+16. 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.

Worked engineering reasoning and boundary conditions

Engineering reference configuration: Payload size (B) = 128; Measured trials per algorithm = 10; Warm-up trials per algorithm = 3. In the classroom model, Verified round trips = 20; AES-GCM median = 0.153558 ms; Ascon median = 0.912441 ms; Ciphertext + tag = 144 B. Actual host timing; do not infer algorithm-only performance from differing language/native implementations. Real AES-GCM via Web Crypto and educational JavaScript Ascon; timing includes implementation and asynchronous host overhead.

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.

Concept animation · progressive data plot

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.

K18 · Comparative AES-GCM and Ascon benchmarking: progressive data plot0.10920.38882750.6684550.94808251.22771AES-GCMAscon1101

Step 1 of 7 · Observation 1

Observation 1

AES-GCM
0.426897
Ascon
0.83813

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

Recall the concept before revealing its explanation.

0 / 3 revealed
K18 · 01 / 08What is controlled?Reveal explanation
Engineering explanation

Payload, AAD, trial count and timed encrypt/decrypt boundary.

K18 · 02 / 08Why alternate order?Reveal explanation
Engineering explanation

To reduce systematic warm-up and ordering effects.

K18 · 03 / 08What is not measured?Reveal explanation
Engineering explanation

MCU speed, memory, energy or an algorithm-only performance difference.

K18 · 04 / 08Why use the same payloads and timing method across AES-GCM and Ascon?Reveal explanation
Engineering reasoning

It controls the workload; compare correctness and distributions under matched conditions rather than incomparable single timings.

K18 · 05 / 08Why not infer embedded energy cost from host timing alone?Reveal explanation
Engineering reasoning

Different hardware acceleration and power characteristics mean host latency is not a measurement of microcontroller energy.

K18 · 06 / 08AES-GCM and Ascon implementations are benchmarked. Select every technically valid statement. A. Use paired conditions and the same workload definition. B. Report implementation and host context with the timings. C. A host timing proves all hardware rankings. D. Changing message lengths between methods isolates algorithm cost.Reveal explanation
Applied scenario

Correct: A. Use paired conditions and the same workload definition.; B. Report implementation and host context with the timings.

K18 · 07 / 08Which engineering mechanism is tested by K18 · Comparative AES-GCM and Ascon benchmarking, and what state or outcome is evaluated?Reveal explanation
Implementation recall

Measure both implementations under paired host conditions; distinguish implementation overhead from algorithm properties.

K18 · 08 / 08For K18 · Comparative AES-GCM and Ascon benchmarking, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance

Copy updated security_extensions.py and ascon_course.py into ~/kali-labs. Run in a fresh mktemp results directory; output is benchmark.json and aead-comparison.csv with 800 data rows (two implementations × four sizes × 100). Compare combined encrypt+decrypt microseconds; Python Ascon versus native-library AES is implementation-level, not a fair isolated algorithm/MCU speed claim. No memory or energy measured.

Loading experiment-specific apparatus…
K18 · Model-linked instrumentation

Visual observation lens

Back to controls ↑

Closed two-condition teaching fixture; actual security validation requires the practical procedure.

Loading instrument…

Awaiting model display.

Experimental instrumentation · A/B

Compare two model conditions

Capture a baseline, change one experimental condition, run the model if required and capture the comparison. Snapshots contain visible controls and display text, not physical sensor readings. Review before exporting.

Open simulation view
Baseline A
Not captured
Comparison B
Not captured

Capture a baseline to begin.

Evidence portfolio →
V19.0 · Contextual AI workspace

Ask your engineering assistants

K18 · current context

Ask Dr. Mohammad locally, or prepare an experiment-aware prompt for ChatGPT, Gemini or Claude. The external providers open in their own tabs; nothing is automatically submitted.

Dr. Mohammad · offline
Dr. Mohammad

Offline curriculum-grounded assistance.

Open local tutor
K18 · Comparative AES-GCM and Ascon benchmarking

Public course objective, displayed commands, source excerpts and procedure. Private assessment content is not collected.

Prepare a contextual AI prompt

0 characters

Common secret and email patterns are redacted on preparation; this is not a comprehensive privacy filter. Review the entire editable prompt, including student work and unpublished research, before sharing. The providers apply their own accounts, privacy settings and limits.

Prepare → review → copy & open your selected provider → paste and submit there.

Run & verify — acceptance checklist

Build verification: Actual AES/Ascon 800 combined timing samples recorded.

Copy updated security_extensions.py and ascon_course.py into ~/kali-labs. Run in a fresh mktemp results directory; output is benchmark.json and aead-comparison.csv with 800 data rows (two implementations × four sizes × 100). Compare combined encrypt+decrypt microseconds; Python Ascon versus native-library AES is implementation-level, not a fair isolated algorithm/MCU speed claim. No memory or energy measured.

Record the actual output, source (mock/model or physical), and any error. A missing tool, timeout or untested external service is not a pass.

Complete lab-by-lab verification report →Open automated verification center → Ask Engineering Copilot →

Independent theoretical exercises

Before the simulation or practical, solve both experiment-specific tasks. List the given inputs, show the intermediate calculation or state trace, identify the expected observation, and state a limitation. Show formulas and intermediate calculations where relevant, or draw the requested state/sequence diagram. These are independent classroom fixtures; where they differ from the reference configuration below, do not treat them as measured values. Compare your predictions with the corresponding experiment afterwards.

01 · Predict and derive using the given inputs

For AES-GCM timings 2,3,4,5,6 ms and Ascon 3,4,5,6,7 ms, calculate median and nearest-rank P95 for each.

02 · Compare or justify using evidence

For 128 bytes and the respective median times, estimate throughput; discuss why these fictional calculations cannot establish hardware superiority.

03 · Experiment interpretation

Experiment interpretation · Independent work

At 128 B, algorithm A median8 µs and B12 µs; at 1024 B A40 µs and B35 µs. Compute ratios B/A and explain limits.

Work is saved locally when browser storage is available. Export it for submission; no remote upload or automatic grade is assigned.

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 · Explain a changed-input result

Independent theoretical exercise · K18-01

Use the reference configuration (Payload size (B) = 128; Measured trials per algorithm = 10; Warm-up trials per algorithm = 3), but change Payload size (B) = 512. One previously recorded run reported AES-GCM median = 0.178582 ms. This is a runtime-dependent measurement, not a deterministic expected output. Explain which factors affect the measurement; propose repeated controlled trials and report their distribution instead of requiring this exact value.

Intermediate · Quantitative comparison

Independent theoretical exercise · K18-02

Two model observations of AES-GCM median are 0.153558 ms (reference) and 0.178582 ms (changed condition). Compute signed change and, when the reference is nonzero, percentage change. Explain why units matter.

Intermediate · Interpret a technical trace

Independent theoretical exercise · K18-03

For Measured trials per algorithm = 12, the model supplies this excerpt from Paired trial results: Trial · Implementation · Elapsed ms · Combined bytes · Nonce bytes · Verified 1 · Ascon · 0.523617 · 144 · 16 · Yes 1 · AES · 0.216756 · 144 · 12 · Yes 2 · AES · 0.086536 · 144 · 12 · Yes 2 · Ascon · 0.95006 · 144 · 16 · Yes 3 · Ascon · 0.585035 · 144 · 16 · Yes Count rows whose Implementation value is exactly “Ascon”, and identify the displayed row numbers. Explain what the count describes.

Advanced · Reverse reasoning

Independent theoretical exercise · K18-04

An observation is Verified round trips = 24. Candidate A uses Payload size (B) = 128; Measured trials per algorithm = 10; Warm-up trials per algorithm = 3. Candidate B changes the listed settings (Measured trials per algorithm = 12) and keeps the remaining settings fixed. Which is consistent with the observation? If both can explain it, say what additional evidence is required.

Advanced · Diagnose a reported mismatch

Independent theoretical exercise · K18-05

A student configures Warm-up trials per algorithm = 5 while preserving all other reference settings, but copies the reference report of AES-GCM median = 0.153558 ms. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

Challenging · Design a controlled verification

Independent theoretical exercise · K18-06

Design a controlled comparison for K18 · Comparative AES-GCM and Ascon benchmarking using reference Payload size (B) = 128; Measured trials per algorithm = 10; Warm-up trials per algorithm = 3 and test Payload size (B) = 512. Specify the changed setting(s), measured metric AES-GCM median, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

Step-by-step experimental procedure

Compare actual host execution distributions and transmitted representations for two AEAD implementations.

1 · Reference workbench configuration

Use the named reference workbench and its reference inputs. Additional live instruments may have different controls; use the matching instrument. Record virtual and practical results separately.

Payload size (B)128
Measured trials per algorithm10
Warm-up trials per algorithm3

2 · Perform the investigation in order

  1. Select 128 bytes, 10 measured trials and 3 warm-ups per algorithm. Inspect the per-trial timings and p50/p95; warm-ups are excluded.
  2. Repeat for 32, 512 and 1024 bytes with identical trial counts. Compare size-dependent differences; both ciphertext-plus-tag lengths must be payload+16.
  3. Inspect 12-byte AES-GCM IV and 16-byte Ascon nonce assumptions. Compare bytes if nonce is carried separately.
  4. Repeat each size and discuss measurement variability and implementation differences.
  5. Run the preserved K18 Python benchmark for its 800 measured host trials; distinguish the Python/native comparison from browser/native versus JavaScript.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
128-byte pairedUse reference inputs aboveVerified round trips: 20Record actual result
32-byte pairedPayload size (B) = 32Verified round trips: 20Record actual result
1024-byte pairedPayload size (B) = 1024Verified round trips: 20Record actual result

4 · Analyze and report

Do not present these host timings as microcontroller energy, RAM or algorithm-only performance.

Required evidence: Paired CSV-equivalent trial data and a limitation statement.

Model boundary: Real AES-GCM via Web Crypto and educational JavaScript Ascon; timing includes implementation and asynchronous host overhead.

Controlled investigation · reproducible evidence

Method. Use the existing reference workbench configuration and the named controlled changes below. A controlled variable stays fixed while the independent variable is intentionally changed; the dependent variable is the resulting observed output. First predict each trial from the Concepts page. Run the baseline, then change only the specified setting and record the outcome. For deterministic traces one execution per case and a repeated verification are sufficient; for timing or stochastic measurements repeat at least five times, recording each run, median and range. Reset to the reference state between independent comparisons.

TrialIndependent changeDependent observation
128-byte pairedUse reference inputs aboveRecord actual outcome and units
32-byte pairedPayload size (B) = 32Record actual outcome and units
1024-byte pairedPayload size (B) = 1024Record actual outcome and units

Evidence: attach the completed comparison table, one trace or screenshot per condition, and actual practical terminal/hardware evidence where applicable. Explain any prediction mismatch and distinguish modeled behavior from measured results.

Loading laboratory-specific procedure…

Python / Google Colab notebook

Original local cryptography reference (ephemeral files); not production validation. Validated locally in a fresh Jupyter kernel. Download, then upload to Google Colab.

Download NotebookOpen Google ColabAll Python notebooks

Independent implementation sequence

  1. 1. Check updated implementation
  2. 2. Execute verification
  3. 3. Record and reflect

Complete practical procedure

1. Check updated implementation

Kali WSL · Bash
cd ~/kali-labs
ls -l security_extensions.py
✓ Expected: security_extensions.py exists; copy the updated file from the toolkit if missing.

2. Execute verification

Kali WSL · Bash
mkdir -p ~/psut-security-results
work=$(mktemp -d ~/psut-security-results/aead-XXXXXX)
cd "$work"
python3 ~/kali-labs/security_extensions.py benchmark > benchmark.json && cat benchmark.json && ls -l aead-comparison.csv
✓ Expected: 800 actual host trials (100 per algorithm per payload); ciphertext plus tag adds 16 bytes for each. CSV and JSON are created. Do not compare this Python Ascon with native AES as a claim about MCU performance.

3. Record and reflect

Notebook action

Record the actual output and compare with the expected decisions.

✓ Expected: Notebook contains actual outputs, acquisition method and limitations.

Experimental notebook

Record your own results. Values are not prefilled or independently verified.

Scientific method and source

800 actual host trials (100 per algorithm per payload); ciphertext plus tag adds 16 bytes for each. CSV and JSON are created. Do not compare this Python Ascon with native AES as a claim about MCU performance. Record all actual outputs; a missing dependency is not a passed security test.

Temporary cryptographic material is removed automatically for K19; the K18 results directory is retained. K20 is a bounded in-memory defensive policy, not a deployed network service.

Download source
Read complete source
PYTHON · Source code
#!/usr/bin/env python3
"""Defensive coursework with fictional records, temporary keys and local certificate files only."""
import argparse, csv, datetime, hashlib, hmac, json, math, os, platform, secrets, ssl, statistics, subprocess, tempfile, time
from pathlib import Path
from cryptography import x509
from cryptography.x509.oid import NameOID, ExtendedKeyUsageOID
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import ascon_course as ascon

def benchmark():
    key=secrets.token_bytes(16); aes=AESGCM(key); ad=b'PSUT fictional telemetry'; rows=[]
    # Same payload, AAD and paired trial counts. Unique nonces within each algorithm.
    # Distinct algorithms and implementations, not an isolated algorithm comparison.
    ak=secrets.token_bytes(16)
    for size in (32,128,512,1024):
        msg=b'x'*size
        for trial in range(110):
            order=('AES-GCM','Ascon-AEAD128') if trial%2==0 else ('Ascon-AEAD128','AES-GCM')
            for name in order:
                n=(size*1000+trial).to_bytes(12 if name=='AES-GCM' else 16,'big')
                t=time.perf_counter_ns()
                if name=='AES-GCM': c=aes.encrypt(n,msg,ad);plain=aes.decrypt(n,c,ad)
                else:c=ascon.encrypt(ak,n,ad,msg);plain=ascon.decrypt(ak,n,ad,c)
                elapsed=(time.perf_counter_ns()-t)/1000
                assert plain==msg and len(c)==size+16
                if trial>=10:rows.append([name,size,trial-9,elapsed,len(c),len(n)])
    with open('aead-comparison.csv','x',newline='') as f:
        w=csv.writer(f);w.writerow(['algorithm','payload_bytes','trial','combined_us','ciphertext_tag_bytes','nonce_bytes']);w.writerows(rows)
    summaries=[]
    for name in ('AES-GCM','Ascon-AEAD128'):
        for size in (32,128,512,1024):
            t=sorted(r[3] for r in rows if r[0]==name and r[1]==size);summaries.append({'algorithm':name,'bytes':size,'n':len(t),'median_us':statistics.median(t),'p95_us':t[math.ceil(.95*len(t))-1]})
    return {'provenance':'actual host timing, synthetic payload','pass':True,'trials':len(rows),'python':platform.python_version(),'machine':platform.machine(),'openssl':ssl.OPENSSL_VERSION,'warmups':10,'summary':summaries,'limitations':'Python teaching Ascon versus cryptography native AES-GCM; not an algorithm-only, MCU, energy or memory comparison. No memory measurements collected.'}

def certificates(directory):
    p=Path(directory);now=datetime.datetime.now(datetime.timezone.utc);key=ec.generate_private_key(ec.SECP256R1());ca=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,'PSUT temporary CA')]);
    def write(label,k,c):
        (p/(label+'.pem')).write_bytes(c.public_bytes(serialization.Encoding.PEM)); f=p/(label+'.key');f.write_bytes(k.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption()));f.chmod(0o600)
    def cert(name,k,root=False,server=False):
        b=x509.CertificateBuilder().subject_name(name).issuer_name(ca).public_key(k.public_key()).serial_number(x509.random_serial_number()).not_valid_before(now-datetime.timedelta(minutes=1)).not_valid_after(now+datetime.timedelta(hours=1)).add_extension(x509.BasicConstraints(ca=root,path_length=0 if root else None),critical=True).add_extension(x509.SubjectKeyIdentifier.from_public_key(k.public_key()),False).add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()),False).add_extension(x509.KeyUsage(digital_signature=not root,content_commitment=False,key_encipherment=False,data_encipherment=False,key_agreement=False,key_cert_sign=root,crl_sign=root,encipher_only=None,decipher_only=None),True)
        if not root:
            b=b.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH if server else ExtendedKeyUsageOID.CLIENT_AUTH]),False)
            if server:b=b.add_extension(x509.SubjectAlternativeName([x509.DNSName('localhost')]),False)
        return b.sign(key,hashes.SHA256())
    root=cert(ca,key,True);write('ca',key,root);issued={}
    for name in ('localhost','sensor','viewer'):
        k=ec.generate_private_key(ec.SECP256R1());c=cert(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,name)]),k,server=name=='localhost');write(name,k,c);issued[name]=c
    def crl(revoke):
        b=x509.CertificateRevocationListBuilder().issuer_name(ca).last_update(now-datetime.timedelta(minutes=1)).next_update(now+datetime.timedelta(hours=1)).add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()),False).add_extension(x509.CRLNumber(2 if revoke else 1),False)
        if revoke:b=b.add_revoked_certificate(x509.RevokedCertificateBuilder().serial_number(issued['sensor'].serial_number).revocation_date(now).build())
        return b.sign(key,hashes.SHA256()).public_bytes(serialization.Encoding.PEM)
    (p/'valid.crl').write_bytes(crl(False));(p/'revoked.crl').write_bytes(crl(True))

def revocation():
    with tempfile.TemporaryDirectory(prefix='psut-crl-') as tmp:
        certificates(tmp);p=Path(tmp);checks=[]
        for label,crl,identity,expected in [('initial client valid','valid','sensor',True),('retired client revoked','revoked','sensor',False),('unrevoked viewer valid','revoked','viewer',True)]:
            r=subprocess.run(['openssl','verify','-CAfile',str(p/'ca.pem'),'-CRLfile',str(p/(crl+'.crl')),'-crl_check','-purpose','sslclient',str(p/(identity+'.pem'))],capture_output=True,text=True,timeout=10)
            msg=(r.stdout+r.stderr).replace(tmp,'<temporary>');passed=r.returncode==0 if expected else r.returncode!=0 and 'certificate revoked' in msg.lower();checks.append({'name':label,'pass':passed,'exit':r.returncode,'observation':msg.strip()})
        return {'source':'actual OpenSSL CRL verification','checks':checks,'pass':all(x['pass'] for x in checks),'limitation':'CRL check must be enabled at relying party. This is not automatic distribution or session termination.'}

def gateway():
    key=secrets.token_bytes(32);highest=0;logs=[];accepted=[]
    def packet(seq,temp):
        raw=json.dumps({'device':'demo-01','seq':seq,'temperature':temp},separators=(',',':'),allow_nan=False).encode();return raw,hmac.digest(key,raw,'sha256')
    def check(raw,tag):
        nonlocal highest
        if len(raw)>512 or not hmac.compare_digest(hmac.digest(key,raw,'sha256'),tag):return 'integrity-rejected'
        try:d=json.loads(raw);good=type(d)==dict and set(d)=={'device','seq','temperature'} and d['device']=='demo-01' and type(d['seq']) is int and 1<=d['seq']<=2**31-1 and type(d['temperature']) in (int,float) and math.isfinite(d['temperature']) and -40<=d['temperature']<=80
        except (ValueError,TypeError,OverflowError):good=False
        if not good:return 'schema-rejected'
        if d['seq']<=highest:return 'replay-rejected'
        highest=d['seq'];accepted.append(d);return 'accepted'
    good=packet(1,25);bad=packet(2,30);tests=[('positive',*good,'accepted'),('duplicate',*good,'replay-rejected'),('tampered',bad[0]+b' ',bad[1],'integrity-rejected'),('invalid range',*packet(2,90),'schema-rejected'),('recovery',*packet(2,26),'accepted')]
    for label,raw,tag,expected in tests:
        actual=check(raw,tag);logs.append({'case':label,'decision':actual,'expected':expected,'pass':actual==expected})
    counts={x:sum(r['decision']==x for r in logs) for x in set(r['decision'] for r in logs)}
    # Deliberately bounded local rule; no real broker logs are claimed.
    return {'source':'actual local gateway policy evaluation of fictional cases','pass':all(x['pass'] for x in logs),'events':logs,'accepted':accepted,'decision_counts':counts,'alert':sum(v for k,v in counts.items() if k!='accepted')>=3,'limitations':'In-memory state, synthetic event monitor, no production gateway or live broker integration. Range checks do not detect all malicious readings.'}

if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('experiment',choices=['benchmark','revocation','gateway']);args=p.parse_args();r=globals()[args.experiment]();print(json.dumps(r,indent=2));raise SystemExit(0 if r['pass'] else 1)

Verification and discussion

800 actual host trials (100 per algorithm per payload); ciphertext plus tag adds 16 bytes for each. CSV and JSON are created. Do not compare this Python Ascon with native AES as a claim about MCU performance.

Explain failed or inconclusive outcomes, save the actual JSON and any CSV, record software versions and reflect on limits. No credentials or real data in evidence.

Record evidence → · Ask Dr. Mohammad →

Python / Google Colab laboratory

K18 · 13 notebook cells · 4 executable Python cells

Complete the theoretical investigation first. Run the cells in order, record actual outputs and compare against your prediction.

How to execute

  1. Download this notebook and open Google Colab. Select File → Upload notebook and choose the downloaded .ipynb.
  2. Read the Markdown instructions before each executable cell. Use a Python runtime, run cells from top to bottom, and resolve imports if necessary.
  3. Perform the baseline and controlled changes. Save the notebook with actual outputs and your written interpretation.

Execution scope: Default computational cells passed isolated local Python execution; physical equipment and live services require separate verification.

01Instructions · Markdown
# K18 · K18 · Comparative AES-GCM and Ascon benchmarking **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Introduction Measure both implementations under paired host conditions; distinguish implementation overhead from algorithm properties. ## How to run 1. Download this notebook from the laboratory page. Open Google Colab → File → Upload notebook. 2. Select a Python CPU runtime. Run cells from top to bottom using Shift+Enter, or Runtime → Run all. 3. Read the printed observations and assertions. Change one parameter at a time and rerun the relevant cell. 4. Save your own outputs and compare them to the portal Experiment tab. **Execution boundary:** Original local cryptography reference (ephemeral files); not production validation. Do not run the hardware or service commands in Colab. No real credentials are needed. The notebook is self-contained.
02Instructions · Markdown
## Experiment-specific preparation Measure both implementations under paired host conditions; distinguish implementation overhead from algorithm properties. **Reference procedure (use the matching simulator/WSL tool where named, not an unrelated service):** 1. Select 128 bytes, 10 measured trials and 3 warm-ups per algorithm. Inspect the per-trial timings and p50/p95; warm-ups are excluded. 2. Repeat for 32, 512 and 1024 bytes with identical trial counts. Compare size-dependent differences; both ciphertext-plus-tag lengths must be payload+16. 3. Inspect 12-byte AES-GCM IV and 16-byte Ascon nonce assumptions. Compare bytes if nonce is carried separately. 4. Repeat each size and discuss measurement variability and implementation differences. 5. Run the preserved K18 Python benchmark for its 800 measured host trials; distinguish the Python/native comparison from browser/native versus JavaScript. **Evidence:** **Boundary:**
03Instructions · Markdown
## 1. Objectives and reference condition - Reproduce the specific computational mechanism in this laboratory. - Inspect the output, compare the reference condition with a changed or rejected condition where implemented, and explain any discrepancy. - Distinguish actual local Python execution from mock, physical and external-service observations. ## 2. Environment check
04Python · executable cell
PYTHON · Code cell
# =====================================================================
# K18 | Code cell 01 | K18 · Comparative AES-GCM and Ascon benchmarking
# Purpose: 1. Objectives and reference condition - Reproduce the specific computational mechanism in this laboratory. - Inspect the output, compare the reference condition with a changed or rejected condition where implem
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
import sys
print("Python",sys.version.split()[0])
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert sys.version_info >= (3,10)
Ask Dr. Mohammad about this cell
05Instructions · Markdown
## 3. Implementation Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
06Python · executable cell
PYTHON · Code cell
# =====================================================================
# K18 | Code cell 02 | K18 · Comparative AES-GCM and Ascon benchmarking
# Purpose: 3. Implementation Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
# 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 ascon for the next computation or reference condition.
ascon = types.ModuleType("ascon_course")
exec('#!/usr/bin/env python3\n"""Byte-oriented educational Ascon-AEAD128, NIST SP 800-232 (2025).\nNot hardened or validated for production. No secret inputs or external services.\n"""\nimport hmac, json, os\nMASK=(1<<64)-1\nIV=0x00001000808c0001\nRC=(0xf0,0xe1,0xd2,0xc3,0xb4,0xa5,0x96,0x87,0x78,0x69,0x5a,0x4b)\ndef rot(x,n): return ((x>>n)|(x<<(64-n)))&MASK\ndef perm(s,rounds):\n    for c in RC[-rounds:]:\n        a,b,d,e,f=s; d^=c\n        a^=f; f^=e; d^=b\n        t=[a,b,d,e,f]; u=[t[i]^((~t[(i+1)%5])&t[(i+2)%5]) for i in range(5)]\n        u[1]^=u[0]; u[0]^=u[4]; u[3]^=u[2]; u[2]=(~u[2])&MASK\n        s[:]=[x^rot(x,i)^rot(x,j) for x,(i,j) in zip(u,[(19,28),(61,39),(1,6),(10,17),(7,41)])]\ndef word(b): return int.from_bytes(b,\'little\')\ndef rate(s): return s[0].to_bytes(8,\'little\')+s[1].to_bytes(8,\'little\')\ndef setrate(s,b): s[0],s[1]=word(b[:8]),word(b[8:])\ndef xor(a,b):return bytes(x^y for x,y in zip(a,b))\ndef init(key,nonce,ad):\n    if len(key)!=16 or len(nonce)!=16:raise ValueError(\'128-bit key and nonce required\')\n    k0,k1=word(key[:8]),word(key[8:]);s=[IV,k0,k1,word(nonce[:8]),word(nonce[8:])];perm(s,12);s[3]^=k0;s[4]^=k1\n    if ad:\n        padded=ad+b\'\\x01\'+b\'\\0\'*((15-len(ad))%16)\n        for i in range(0,len(padded),16):setrate(s,xor(rate(s),padded[i:i+16]));perm(s,8)\n    s[4]^=1<<63\n    return s,k0,k1\ndef finish(s,k0,k1):\n    s[2]^=k0;s[3]^=k1;perm(s,12);s[3]^=k0;s[4]^=k1\n    return s[3].to_bytes(8,\'little\')+s[4].to_bytes(8,\'little\')\ndef encrypt(key,nonce,ad,plain):\n    s,k0,k1=init(key,nonce,ad);out=bytearray()\n    for i in range(0,len(plain)//16*16,16):\n        setrate(s,xor(rate(s),plain[i:i+16]));out.extend(rate(s));perm(s,8)\n    tail=plain[len(plain)//16*16:];setrate(s,xor(rate(s),tail+b\'\\x01\'+b\'\\0\'*(15-len(tail))));out.extend(rate(s)[:len(tail)])\n    return bytes(out)+finish(s,k0,k1)\ndef decrypt(key,nonce,ad,combined):\n    if len(combined)<16:raise ValueError(\'Missing tag\')\n    c,tag=combined[:-16],combined[-16:];s,k0,k1=init(key,nonce,ad);out=bytearray()\n    for i in range(0,len(c)//16*16,16):\n        block=c[i:i+16];out.extend(xor(rate(s),block));setrate(s,block);perm(s,8)\n    tail=c[len(c)//16*16:];r=rate(s);out.extend(xor(r,tail));new=bytearray(tail+r[len(tail):]);new[len(tail)]^=1;setrate(s,new)\n    if not hmac.compare_digest(tag,finish(s,k0,k1)):raise ValueError(\'Authentication failed\')\n    return bytes(out)\ndef checks():\n    # Independent RustCrypto ascon-aead 0.6.0 test vector Count=1 (SP 800-232).\n    # https://docs.rs/crate/ascon-aead/0.6.0/source/tests/data/ascon128.txt\n    k=bytes(range(16));n=k;expected=bytes.fromhex(\'4427D64B8E1E1451FC445960F0839BB0\');actual=encrypt(k,n,b\'\',b\'\')\n    results=[{\'control\':\'independent empty-message KAT\',\'pass\':actual==expected,\'actual\':actual.hex(),\'expected\':expected.hex()}]\n    for count,ml,al,hexout in [(2,0,1,\'103AB79D913A0321287715A979BB8585\'),(33,0,32,\'22133A313FBF0B38029A45870AADC542\'),(34,1,0,\'E79F58F1F541FC51B5D438F8E1DD03F147\'),(35,1,1,\'25EB4B700ED4AC8517DCBA20F673292230\'),(53,1,19,\'64E8A535661ECD9BD9986CEA0A46A8556B\')]:\n        expected=bytes.fromhex(hexout);pt=bytes(range(ml));ad=bytes(range(al));actual=encrypt(k,n,ad,pt)\n        results.append({\'control\':f\'independent KAT {count}\',\'pass\':actual==expected and decrypt(k,n,ad,expected)==pt,\'actual\':actual.hex(),\'expected\':expected.hex()})\n    # Fresh key per run, unique nonce for every encryption. Vectors use fixed public inputs only.\n    k=os.urandom(16)\n    for size in [0,1,15,16,17,31,32,33,128]:\n        for alen in [0,1,16,17]:\n            nonce=(size*100+alen).to_bytes(16,\'little\');msg=bytes(range(size));ad=b\'A\'*alen;ct=encrypt(k,nonce,ad,msg)\n            results.append({\'control\':f\'roundtrip-{size}-{alen}\',\'pass\':decrypt(k,nonce,ad,ct)==msg})\n            for label,nn,aa,cc in [(\'tag\',nonce,ad,ct[:-1]+bytes([ct[-1]^1])),(\'associated-data\',nonce,ad+b\'!\',ct),(\'nonce\',bytes([nonce[0]^1])+nonce[1:],ad,ct)]+([(\'ciphertext\',nonce,ad,bytes([ct[0]^1])+ct[1:])] if size else []):\n                try:decrypt(k,nn,aa,cc);ok=False\n                except ValueError:ok=True\n                results.append({\'control\':f\'reject-{label}-{size}-{alen}\',\'pass\':ok})\n    return {\'schema\':\'psut-security-evidence-157\',\'experiment\':\'K15\',\'source\':\'actual-local-educational-crypto\',\'implementation\':\'byte-oriented teaching implementation; not production hardened\',\'checks\':results,\'pass\':all(x[\'pass\'] for x in results)}\n', ascon.__dict__)
# Set sys.modules['ascon_course'] for the next computation or reference condition.
sys.modules["ascon_course"]=ascon
Ask Dr. Mohammad about this cell
07Instructions · Markdown
### Step 2 · Run the reference calculation Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
08Python · executable cell
PYTHON · Code cell
# =====================================================================
# K18 | Code cell 03 | K18 · Comparative AES-GCM and Ascon benchmarking
# Purpose: benchmark
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
import csv, math, platform, secrets, ssl, statistics, time

from cryptography.hazmat.primitives.ciphers.aead import AESGCM

import ascon_course as ascon

# Define the reusable operation benchmark; keep its logic separate from the trial.
def benchmark():
    key=secrets.token_bytes(16); aes=AESGCM(key); ad=b'PSUT fictional telemetry'; rows=[]
    # Same payload, AAD and paired trial counts. Unique nonces within each algorithm.
    # Distinct algorithms and implementations, not an isolated algorithm comparison.
    ak=secrets.token_bytes(16)
    for size in (32,128,512,1024):
        msg=b'x'*size
        for trial in range(110):
            order=('AES-GCM','Ascon-AEAD128') if trial%2==0 else ('Ascon-AEAD128','AES-GCM')
            for name in order:
                n=(size*1000+trial).to_bytes(12 if name=='AES-GCM' else 16,'big')
                t=time.perf_counter_ns()
                if name=='AES-GCM': c=aes.encrypt(n,msg,ad);plain=aes.decrypt(n,c,ad)
                else:c=ascon.encrypt(ak,n,ad,msg);plain=ascon.decrypt(ak,n,ad,c)
                elapsed=(time.perf_counter_ns()-t)/1000
                assert plain==msg and len(c)==size+16
                if trial>=10:rows.append([name,size,trial-9,elapsed,len(c),len(n)])
    with open('aead-comparison.csv','x',newline='') as f:
        w=csv.writer(f);w.writerow(['algorithm','payload_bytes','trial','combined_us','ciphertext_tag_bytes','nonce_bytes']);w.writerows(rows)
    summaries=[]
    for name in ('AES-GCM','Ascon-AEAD128'):
        for size in (32,128,512,1024):
            t=sorted(r[3] for r in rows if r[0]==name and r[1]==size);summaries.append({'algorithm':name,'bytes':size,'n':len(t),'median_us':statistics.median(t),'p95_us':t[math.ceil(.95*len(t))-1]})
    return {'provenance':'actual host timing, synthetic payload','pass':True,'trials':len(rows),'python':platform.python_version(),'machine':platform.machine(),'openssl':ssl.OPENSSL_VERSION,'warmups':10,'summary':summaries,'limitations':'Python teaching Ascon versus cryptography native AES-GCM; not an algorithm-only, MCU, energy or memory comparison. No memory measurements collected.'}
Ask Dr. Mohammad about this cell
09Instructions · Markdown
### Step 3 · Run the reference calculation Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
10Python · executable cell
PYTHON · Code cell
# =====================================================================
# K18 | Code cell 04 | K18 · Comparative AES-GCM and Ascon benchmarking
# Purpose: Step 3 · Run the reference calculation Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
import tempfile,os
# Set old for the next computation or reference condition.
old=os.getcwd()
# Limit resource lifetime to this block so files, sockets or temporary state are cleaned up.
with tempfile.TemporaryDirectory() as d:
    os.chdir(d)
    try: result=benchmark()
    finally: os.chdir(old)
print(result)
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert result is not None and (not isinstance(result,dict) or result.get("pass",result.get("passed",True)))
Ask Dr. Mohammad about this cell
11Instructions · Markdown
## Original portal implementation (reference only) These are the actual laboratory snippets. They are retained for comparison; follow the portal setup for WSL, hardware or services. They are **not** executed by Run all. ```bash mkdir -p ~/psut-security-results work=$(mktemp -d ~/psut-security-results/aead-XXXXXX) cd "$work" python3 ~/kali-labs/security_extensions.py benchmark > benchmark.json && cat benchmark.json && ls -l aead-comparison.csv ``` ```python #!/usr/bin/env python3 """Defensive coursework with fictional records, temporary keys and local certificate files only.""" import argparse, csv, datetime, hashlib, hmac, json, math, os, platform, secrets, ssl, statistics, subprocess, tempfile, time from pathlib import Path from cryptography import x509 from cryptography.x509.oid import NameOID, ExtendedKeyUsageOID from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.ciphers.aead import AESGCM import ascon_course as ascon def benchmark(): key=secrets.token_bytes(16); aes=AESGCM(key); ad=b'PSUT fictional telemetry'; rows=[] # Same payload, AAD and paired trial counts. Unique nonces within each algorithm. # Distinct algorithms and implementations, not an isolated algorithm comparison. ak=secrets.token_bytes(16) for size in (32,128,512,1024): msg=b'x'*size for trial in range(110): order=('AES-GCM','Ascon-AEAD128') if trial%2==0 else ('Ascon-AEAD128','AES-GCM') for name in order: n=(size*1000+trial).to_bytes(12 if name=='AES-GCM' else 16,'big') t=time.perf_counter_ns() if name=='AES-GCM': c=aes.encrypt(n,msg,ad);plain=aes.decrypt(n,c,ad) else:c=ascon.encrypt(ak,n,ad,msg);plain=ascon.decrypt(ak,n,ad,c) elapsed=(time.perf_counter_ns()-t)/1000 assert plain==msg and len(c)==size+16 if trial>=10:rows.append([name,size,trial-9,elapsed,len(c),len(n)]) with open('aead-comparison.csv','x',newline='') as f: w=csv.writer(f);w.writerow(['algorithm','payload_bytes','trial','combined_us','ciphertext_tag_bytes','nonce_bytes']);w.writerows(rows) summaries=[] for name in ('AES-GCM','Ascon-AEAD128'): for size in (32,128,512,1024): t=sorted(r[3] for r in rows if r[0]==name and r[1]==size);summaries.append({'algorithm':name,'bytes':size,'n':len(t),'median_us':statistics.median(t),'p95_us':t[math.ceil(.95*len(t))-1]}) return {'provenance':'actual host timing, synthetic payload','pass':True,'trials':len(rows),'python':platform.python_version(),'machine':platform.machine(),'openssl':ssl.OPENSSL_VERSION,'warmups':10,'summary':summaries,'limitations':'Python teaching Ascon versus cryptography native AES-GCM; not an algorithm-only, MCU, energy or memory comparison. No memory measurements collected.'} def certificates(directory): p=Path(directory);now=datetime.datetime.now(datetime.timezone.utc);key=ec.generate_private_key(ec.SECP256R1());ca=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,'PSUT temporary CA')]); def write(label,k,c): (p/(label+'.pem')).write_bytes(c.public_bytes(serialization.Encoding.PEM)); f=p/(label+'.key');f.write_bytes(k.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption()));f.chmod(0o600) def cert(name,k,root=False,server=False): b=x509.CertificateBuilder().subject_name(name).issuer_name(ca).public_key(k.public_key()).serial_number(x509.random_serial_number()).not_valid_before(now-datetime.timedelta(minutes=1)).not_valid_after(now+datetime.timedelta(hours=1)).add_extension(x509.BasicConstraints(ca=root,path_length=0 if root else None),critical=True).add_extension(x509.SubjectKeyIdentifier.from_public_key(k.public_key()),False).add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()),False).add_extension(x509.KeyUsage(digital_signature=not root,content_commitment=False,key_encipherment=False,data_encipherment=False,key_agreement=False,key_cert_sign=root,crl_sign=root,encipher_only=None,decipher_only=None),True) if not root: b=b.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH if server else ExtendedKeyUsageOID.CLIENT_AUTH]),False) if server:b=b.add_extension(x509.SubjectAlternativeName([x509.DNSName('localhost')]),False) return b.sign(key,hashes.SHA256()) root=cert(ca,key,True);write('ca',key,root);issued={} for name in ('localhost','sensor','viewer'): k=ec.generate_private_key(ec.SECP256R1());c=cert(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,name)]),k,server=name=='localhost');write(name,k,c);issued[name]=c def crl(revoke): b=x509.CertificateRevocationListBuilder().issuer_name(ca).last_update(now-datetime.timedelta(minutes=1)).next_update(now+datetime.timedelta(hours=1)).add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()),False).add_extension(x509.CRLNumber(2 if revoke else 1),False) if revoke:b=b.add_revoked_certificate(x509.RevokedCertificateBuilder().serial_number(issued['sensor'].serial_number).revocation_date(now).build()) return b.sign(key,hashes.SHA256()).public_bytes(serialization.Encoding.PEM) (p/'valid.crl').write_bytes(crl(False));(p/'revoked.crl').write_bytes(crl(True)) def revocation(): with tempfile.TemporaryDirectory(prefix='psut-crl-') as tmp: certificates(tmp);p=Path(tmp);checks=[] for label,crl,identity,expected in [('initial client valid','valid','sensor',True),('retired client revoked','revoked','sensor',False),('unrevoked viewer valid','revoked','viewer',True)]: r=subprocess.run(['openssl','verify','-CAfile',str(p/'ca.pem'),'-CRLfile',str(p/(crl+'.crl')),'-crl_check','-purpose','sslclient',str(p/(identity+'.pem'))],capture_output=True,text=True,timeout=10) msg=(r.stdout+r.stderr).replace(tmp,'<temporary>');passed=r.returncode==0 if expected else r.returncode!=0 and 'certificate revoked' in msg.lower();checks.append({'name':label,'pass':passed,'exit':r.returncode,'observation':msg.strip()}) return {'source':'actual OpenSSL CRL verification','checks':checks,'pass':all(x['pass'] for x in checks),'limitation':'CRL check must be enabled at relying party. This is not automatic distribution or session termination.'} def gateway(): key=secrets.token_bytes(32);highest=0;logs=[];accepted=[] def packet(seq,temp): raw=json.dumps({'device':'demo-01','seq':seq,'temperature':temp},separators=(',',':'),allow_nan=False).encode();return raw,hmac.digest(key,raw,'sha256') def check(raw,tag): nonlocal highest if len(raw)>512 or not hmac.compare_digest(hmac.digest(key,raw,'sha256'),tag):return 'integrity-rejected' try:d=json.loads(raw);good=type(d)==dict and set(d)=={'device','seq','temperature'} and d['device']=='demo-01' and type(d['seq']) is int and 1<=d['seq']<=2**31-1 and type(d['temperature']) in (int,float) and math.isfinite(d['temperature']) and -40<=d['temperature']<=80 except (ValueError,TypeError,OverflowError):good=False if not good:return 'schema-rejected' if d['seq']<=highest:return 'replay-rejected' highest=d['seq'];accepted.append(d);return 'accepted' good=packet(1,25);bad=packet(2,30);tests=[('positive',*good,'accepted'),('duplicate',*good,'replay-rejected'),('tampered',bad[0]+b' ',bad[1],'integrity-rejected'),('invalid range',*packet(2,90),'schema-rejected'),('recovery',*packet(2,26),'accepted')] for label,raw,tag,expected in tests: actual=check(raw,tag);logs.append({'case':label,'decision':actual,'expected':expected,'pass':actual==expected}) counts={x:sum(r['decision']==x for r in logs) for x in set(r['decision'] for r in logs)} # Deliberately bounded local rule; no real broker logs are claimed. return {'source':'actual local gateway policy evaluation of fictional cases','pass':all(x['pass'] for x in logs),'events':logs,'accepted':accepted,'decision_counts':counts,'alert':sum(v for k,v in counts.items() if k!='accepted')>=3,'limitations':'In-memory state, synthetic event monitor, no production gateway or live broker integration. Range checks do not detect all malicious readings.'} if __name__=='__main__': p=argparse.ArgumentParser();p.add_argument('experiment',choices=['benchmark','revocation','gateway']);args=p.parse_args();r=globals()[args.experiment]();print(json.dumps(r,indent=2));raise SystemExit(0 if r['pass'] else 1) ```
12Instructions · Markdown
## 4. Results and analysis Record the actual output and whether the assertions pass. Identify a parameter to vary, state your prediction, repeat the reference calculation, then explain the changed result. | Trial | Configuration | Observation | Interpretation | |---|---|---|---| | A | Reference | | | | B | One controlled change | | | | C | Reference repeat | | | **Limitations:** Original local cryptography reference (ephemeral files); not production validation. Notebook success does not certify external equipment or services.
13Instructions · 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. Repeat for 32, 512 and 1024 bytes with identical trial counts. Compare size-dependent differences; both ciphertext-plus-tag lengths must be payload+16. 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.
Shared research workbenches · network designer & advanced studies
Concurrent-device simulation & Monte Carlo research
Distributed digital twin · topology, protocol & battery research