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

K15 · Ascon-AEAD128 · lightweight authenticated encryption

Ask Dr. Mohammad · K15 →

Apply byte-oriented Ascon-AEAD128 and distinguish encryption, authentication and nonce uniqueness.

← Security range
Design experiment & verify evidence →
K15 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Kali & IoT securityK15 · Ascon-AEAD128 · lightweight authenticated encryption

Before you start

Complete K01 and K08. Copy the updated Kali toolkit file into ~/kali-labs. Run as a normal Kali user; no additional packages or public services are needed.

Learning outcome

Apply byte-oriented Ascon-AEAD128 and distinguish encryption, authentication and nonce uniqueness.

Updated Kali toolkit
K15 · Academic orientation

Scope and objectives

Scope of the experiment

Apply byte-oriented Ascon-AEAD128 and distinguish encryption, authentication and nonce uniqueness.

The focus of this experiment is to trace Ascon-AEAD128 inputs, associated data and authentication result. Students then compare valid and tampered local messages using the supplied implementation, and verify known-answer behavior and distinguish nonce requirements. 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

  • Trace Ascon-AEAD128 inputs, associated data and authentication result.
  • Compare valid and tampered local messages using the supplied implementation.
  • Verify known-answer behavior and distinguish nonce requirements.
  • Identify the configured inputs (Input source; Plaintext; Associated data; Receiver input) 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 trace Ascon-AEAD128 inputs, associated data and authentication result, compare valid and tampered local messages using the supplied implementation, and verify known-answer behavior and distinguish nonce requirements.

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 known-answer behavior and distinguish nonce requirements. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to K16 · Authenticated audit log verification.

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 · Ascon-AEAD128 state and authentication laboratory

Lightweight AEAD deployment check — Known key + nonce / public test fixture; Associated data / authenticated not encrypted; Ascon-AEAD128 / p12 and p8; Verify tag / reject altered data; Host timing / compare equal message sizes
Five 64-bit words and the three permutation layers.

Scientific foundations and analytical reasoning

Ascon-AEAD128 uses a 320-bit state, 128-bit rate and capacity 192 bits; p12 initializes/finalizes and p8 processes full intermediate blocks.

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 · Ascon state and authentication

Ascon-AEAD128 uses five 64-bit words, a 128-bit rate, 192-bit capacity, a 128-bit key and nonce and a 128-bit tag. The public permutation applies round constants, vertical nonlinear substitution and rotations/XOR diffusion. Standardized padding and byte encoding differ from legacy Ascon versions.

Worked example and engineering interpretation

For 17 bytes of plaintext the ciphertext is 17 bytes plus a 16-byte tag, excluding nonce and other metadata. The first full 16-byte block and padded final byte follow different processing steps. Authentication alone does not establish message freshness; maintain a nonce and replay policy.

Engineering principles · additional worked teaching example

Ascon-AEAD128 is lightweight authenticated encryption. Nonce uniqueness under a key and verification of AAD/tag are essential. A 20-byte payload with a 16-byte authentication tag has 36-byte ciphertext/tag output before explicit nonce or framing.

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 K15 · Ascon-AEAD128 · lightweight authenticated encryption

Apply byte-oriented Ascon-AEAD128 and distinguish encryption, authentication and nonce uniqueness.

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: Apply byte-oriented Ascon-AEAD128 and distinguish encryption, authentication and nonce uniqueness.

  1. Select public empty KAT, no fault. Check tag 4427d64b8e1e1451fc445960f0839bb0 against the independent reference. Fixed key and nonce are public test inputs only.
  2. Switch to teaching message and enter 15 ASCII bytes, then 16, then 17. Inspect the number of p8 message steps and the mandatory final padded block.
  3. Enter nonempty AAD and inspect absorption plus domain separation. Compare ciphertext and tag size; AAD is authenticated but not encrypted into the ciphertext.
  4. Modify tag, associated data and nonce separately; each must reject. Try ciphertext modification with a nonempty message.

Reference check:

Model boundary:

Independent task and submission evidence

2. Switch to teaching message and enter 15 ASCII bytes, then 16, then 17. Inspect the number of p8 message steps and the mandatory final padded block. 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: Input source = teaching message; Plaintext = IoT reading 25.0; Associated data = demo-device; Receiver input = none. In the classroom model, Authentication = Accepted; Plaintext bytes = 16 B; Ciphertext + tag = 32 B; KAT match = Not selected. The final authentication decision uses the recomputed tag; changing authenticated inputs does not simply toggle a result. Actual educational JavaScript port of the bundled NIST SP 800-232 implementation. State is exposed only for public/fictional teaching inputs; not production-hardened or an MCU benchmark.

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 · independent state notebook

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.

K15 · Ascon-AEAD128 · lightweight authenticated encryption: independent state notebook1234567Load IV / key / noncex000001000808c0001x145a6a3c7afff5367x2e0eeb48a73e3092ex3d32c87da60244649x4968f65f439882f5a

Step 1 of 7 · Load IV / key / nonce

Load IV / key / nonce

phase
Load IV / key / nonce
x0
00001000808c0001
x1
45a6a3c7afff5367
x2
e0eeb48a73e3092e
x3
d32c87da60244649
x4
968f65f439882f5a

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

Recall the concept before revealing its explanation.

0 / 3 revealed
K15 · 01 / 08Why use a unique nonce?Reveal explanation
Engineering explanation

AEAD requires nonce uniqueness under a given key; never reuse a production nonce.

K15 · 02 / 08What does associated data protect?Reveal explanation
Engineering explanation

It is authenticated but not encrypted; altered associated data must fail verification.

K15 · 03 / 08Does passing a KAT certify a library?Reveal explanation
Engineering explanation

No. Known-answer vectors check selected algorithm behavior, not side-channel resistance or product certification.

K15 · 04 / 08What must be unique under an Ascon-AEAD128 key?Reveal explanation
Engineering reasoning

Use a unique nonce for each encryption under the same key, following the documented algorithm requirements.

K15 · 05 / 08What is associated data?Reveal explanation
Engineering reasoning

Data authenticated but not encrypted; modification must cause verification failure even when ciphertext is unchanged.

K15 · 06 / 08Ascon-AEAD128 protects a message. Select every technically valid statement. A. Nonce uniqueness under a key is required. B. Altered authenticated data must fail verification. C. A nonce is necessarily a secret password. D. Authentication tags are used to compress plaintext.Reveal explanation
Applied scenario

Correct: A. Nonce uniqueness under a key is required.; B. Altered authenticated data must fail verification.

K15 · 07 / 08Which engineering mechanism is tested by K15 · Ascon-AEAD128 · lightweight authenticated encryption, and what state or outcome is evaluated?Reveal explanation
Implementation recall

Apply byte-oriented Ascon-AEAD128 and distinguish encryption, authentication and nonce uniqueness.

K15 · 08 / 08For K15 · Ascon-AEAD128 · lightweight authenticated encryption, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance

Run ascon_course.py and require overall pass true, 182 checks (6 known-answer, 36 round trip, 140 tamper controls). Save stdout JSON in a fresh file. Reference vectors compare independently published expected bytes; the Python implementation is not certified or side-channel hardened.

Loading experiment-specific apparatus…
K15 · 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

K15 · 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
K15 · Ascon-AEAD128 · lightweight authenticated encryption

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 Ascon 182 controls passed.

Run ascon_course.py and require overall pass true, 182 checks (6 known-answer, 36 round trip, 140 tamper controls). Save stdout JSON in a fresh file. Reference vectors compare independently published expected bytes; the Python implementation is not certified or side-channel hardened.

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 a 17-byte plaintext and 16-byte rate, divide into full and final partial blocks; state how many ciphertext bytes and tag bytes are transmitted.

02 · Compare or justify using evidence

Draw initialization, AD absorption, domain separation, message processing and finalization; predict rejection for modified AD, ciphertext or tag. Explain nonce uniqueness.

03 · Security calculation

Security calculation · Independent work

For 40 bytes plaintext, 16 B explicit nonce and 16 B tag, calculate envelope length and explain behavior on an altered tag.

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

Use the reference configuration (Input source = teaching message; Plaintext = IoT reading 25.0; Associated data = demo-device; Receiver input = none), but change Receiver input = ciphertext. The model reports Authentication = Rejected. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.

Intermediate · Interpret a state transition

Independent theoretical exercise · K15-02

The reference model reports Authentication: Accepted. Under Receiver input = ciphertext it reports Rejected. Explain which configured condition changed and what the two outputs establish, and what they do not establish.

Intermediate · Interpret a technical trace

Independent theoretical exercise · K15-03

For Input source = public empty KAT, the model supplies this excerpt from Ascon state trace: Phase · x0 · x1 · x2 · x3 · x4 Load IV / key / nonce · 00001000808c0001 · 0706050403020100 · 0f0e0d0c0b0a0908 · 0706050403020100 · 0f0e0d0c0b0a0908 Initialization p12 + key · e94ca1d68ad071e7 · ec7a5fc285aed974 · afe01d6bf4bcb26c · 9216fd8172857e38 · 786a1691b9b11607 Domain separation · e94ca1d68ad071e7 · ec7a5fc285aed974 · afe01d6bf4bcb26c · 9216fd8172857e38 · f86a1691b9b11607 Padded final message block · e94ca1d68ad071e6 · ec7a5fc285aed974 · afe01d6bf4bcb26c · 9216fd8172857e38 · f86a1691b9b11607 Finalization p12 + tag · df2aff296c2a4013 · 3e8e253584338202 · 89e17b1c4bc2d9b1 · 51141e8e4bd62744 · b09b83f0605944fc Count rows whose x0 value is exactly “e94ca1d68ad071e7”, and identify the displayed row numbers. Explain what the count describes.

Advanced · Reverse reasoning

Independent theoretical exercise · K15-04

An observation is Plaintext bytes = 0 B. Candidate A uses Input source = teaching message; Plaintext = IoT reading 25.0; Associated data = demo-device; Receiver input = none. Candidate B changes the listed settings (Input source = public empty KAT) 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 · K15-05

A student configures Receiver input = tag while preserving all other reference settings, but copies the reference report of Authentication = Accepted. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

Challenging · Design a controlled verification

Independent theoretical exercise · K15-06

Design a controlled comparison for K15 · Ascon-AEAD128 · lightweight authenticated encryption using reference Input source = teaching message; Plaintext = IoT reading 25.0; Associated data = demo-device; Receiver input = none and test Receiver input = ciphertext. Specify the changed setting(s), measured metric Authentication, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

Step-by-step experimental procedure

Verify Ascon-AEAD128 round trips, public known-answer vectors and tamper rejection while tracing the permutation state.

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.

Input sourceteaching message
PlaintextIoT reading 25.0
Associated datademo-device
Receiver inputnone

2 · Perform the investigation in order

  1. Select public empty KAT, no fault. Check tag 4427d64b8e1e1451fc445960f0839bb0 against the independent reference. Fixed key and nonce are public test inputs only.
  2. Switch to teaching message and enter 15 ASCII bytes, then 16, then 17. Inspect the number of p8 message steps and the mandatory final padded block.
  3. Enter nonempty AAD and inspect absorption plus domain separation. Compare ciphertext and tag size; AAD is authenticated but not encrypted into the ciphertext.
  4. Modify tag, associated data and nonce separately; each must reject. Try ciphertext modification with a nonempty message.
  5. Run python3 ascon_course.py in the supplied toolkit to execute the six independent KATs and the local negative controls.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
Fresh round tripUse reference inputs aboveAuthentication: AcceptedRecord actual result
Independent empty vectorInput source = public empty KATKAT match: Yes; Authentication: AcceptedRecord actual result
Tag alterationReceiver input = tagAuthentication: RejectedRecord actual result
Associated-data alterationReceiver input = associated dataAuthentication: RejectedRecord actual result
Nonce alterationReceiver input = nonceAuthentication: RejectedRecord actual result

4 · Analyze and report

Relate the 128-bit rate, 320-bit state and p12/p8 phases to the observed trace.

Required evidence: Known-answer result, 15/16/17-byte traces and tamper decisions.

Model boundary: Actual educational JavaScript port of the bundled NIST SP 800-232 implementation. State is exposed only for public/fictional teaching inputs; not production-hardened or an MCU benchmark.

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
Fresh round tripUse reference inputs aboveRecord actual outcome and units
Independent empty vectorInput source = public empty KATRecord actual outcome and units
Tag alterationReceiver input = tagRecord actual outcome and units
Associated-data alterationReceiver input = associated dataRecord 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 defensive reference; ephemeral keys/files. Validated locally in a fresh Jupyter kernel. Download, then upload to Google Colab.

Download NotebookOpen Google ColabAll Python notebooks

Independent implementation sequence

  1. 1. Verify updated toolkit file
  2. 2. Run the local defensive controls
  3. 3. Save actual verification evidence

Practical procedure

1. Verify updated toolkit file

Kali WSL · Bash
cd ~/kali-labs
ls -l ascon_course.py
✓ Expected: The named Python file exists. If missing, copy it from the updated Kali toolkit; do not reinstall Kali.

2. Run the local defensive controls

Kali WSL · Bash
cd ~/kali-labs
python3 ascon_course.py
✓ Expected: 182 passing checks: six independent known-answer vectors and 176 round-trip or alteration checks. The program exits nonzero if any control fails.

3. Save actual verification evidence

Kali WSL · Bash
cd ~/kali-labs
mkdir -p ~/psut-security-results
python3 ascon_course.py > ~/psut-security-results/K15-evidence.json && cat ~/psut-security-results/K15-evidence.json
✓ Expected: The JSON records the actual controls and overall pass value. This repeat replaces the named evidence file; rename it first to preserve previous runs.

Experimental notebook

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

Scientific method

The implementation follows NIST SP 800-232 byte ordering, permutation, padding and domain separation. It is an educational Python implementation, not constant-time or production-hardened. Fixed public vector inputs are only for tests. Compare actual and expected outputs, check negative controls, and do not benchmark it as a microcontroller implementation. NIST SP 800-232 · Independent reference vectors

Read the complete source code
PYTHON · Source code
#!/usr/bin/env python3
"""Byte-oriented educational Ascon-AEAD128, NIST SP 800-232 (2025).
Not hardened or validated for production. No secret inputs or external services.
"""
import hmac, json, os
MASK=(1<<64)-1
IV=0x00001000808c0001
RC=(0xf0,0xe1,0xd2,0xc3,0xb4,0xa5,0x96,0x87,0x78,0x69,0x5a,0x4b)
def rot(x,n): return ((x>>n)|(x<<(64-n)))&MASK
def perm(s,rounds):
    for c in RC[-rounds:]:
        a,b,d,e,f=s; d^=c
        a^=f; f^=e; d^=b
        t=[a,b,d,e,f]; u=[t[i]^((~t[(i+1)%5])&t[(i+2)%5]) for i in range(5)]
        u[1]^=u[0]; u[0]^=u[4]; u[3]^=u[2]; u[2]=(~u[2])&MASK
        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)])]
def word(b): return int.from_bytes(b,'little')
def rate(s): return s[0].to_bytes(8,'little')+s[1].to_bytes(8,'little')
def setrate(s,b): s[0],s[1]=word(b[:8]),word(b[8:])
def xor(a,b):return bytes(x^y for x,y in zip(a,b))
def init(key,nonce,ad):
    if len(key)!=16 or len(nonce)!=16:raise ValueError('128-bit key and nonce required')
    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
    if ad:
        padded=ad+b'\x01'+b'\0'*((15-len(ad))%16)
        for i in range(0,len(padded),16):setrate(s,xor(rate(s),padded[i:i+16]));perm(s,8)
    s[4]^=1<<63
    return s,k0,k1
def finish(s,k0,k1):
    s[2]^=k0;s[3]^=k1;perm(s,12);s[3]^=k0;s[4]^=k1
    return s[3].to_bytes(8,'little')+s[4].to_bytes(8,'little')
def encrypt(key,nonce,ad,plain):
    s,k0,k1=init(key,nonce,ad);out=bytearray()
    for i in range(0,len(plain)//16*16,16):
        setrate(s,xor(rate(s),plain[i:i+16]));out.extend(rate(s));perm(s,8)
    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)])
    return bytes(out)+finish(s,k0,k1)
def decrypt(key,nonce,ad,combined):
    if len(combined)<16:raise ValueError('Missing tag')
    c,tag=combined[:-16],combined[-16:];s,k0,k1=init(key,nonce,ad);out=bytearray()
    for i in range(0,len(c)//16*16,16):
        block=c[i:i+16];out.extend(xor(rate(s),block));setrate(s,block);perm(s,8)
    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)
    if not hmac.compare_digest(tag,finish(s,k0,k1)):raise ValueError('Authentication failed')
    return bytes(out)
def checks():
    # Independent RustCrypto ascon-aead 0.6.0 test vector Count=1 (SP 800-232).
    # https://docs.rs/crate/ascon-aead/0.6.0/source/tests/data/ascon128.txt
    k=bytes(range(16));n=k;expected=bytes.fromhex('4427D64B8E1E1451FC445960F0839BB0');actual=encrypt(k,n,b'',b'')
    results=[{'control':'independent empty-message KAT','pass':actual==expected,'actual':actual.hex(),'expected':expected.hex()}]
    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')]:
        expected=bytes.fromhex(hexout);pt=bytes(range(ml));ad=bytes(range(al));actual=encrypt(k,n,ad,pt)
        results.append({'control':f'independent KAT {count}','pass':actual==expected and decrypt(k,n,ad,expected)==pt,'actual':actual.hex(),'expected':expected.hex()})
    # Fresh key per run, unique nonce for every encryption. Vectors use fixed public inputs only.
    k=os.urandom(16)
    for size in [0,1,15,16,17,31,32,33,128]:
        for alen in [0,1,16,17]:
            nonce=(size*100+alen).to_bytes(16,'little');msg=bytes(range(size));ad=b'A'*alen;ct=encrypt(k,nonce,ad,msg)
            results.append({'control':f'roundtrip-{size}-{alen}','pass':decrypt(k,nonce,ad,ct)==msg})
            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 []):
                try:decrypt(k,nn,aa,cc);ok=False
                except ValueError:ok=True
                results.append({'control':f'reject-{label}-{size}-{alen}','pass':ok})
    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)}
if __name__=='__main__':
    r=checks();print(json.dumps(r,indent=2));raise SystemExit(0 if r['pass'] else 1)
Download source file

Verification and discussion

Record the actual JSON output, Python environment, expected versus observed decisions, and any failed or inconclusive controls. Explain what is not established by these tests. Keep fictional inputs and actual local execution distinct.

Record evidence in engineering notebook →

Ask Dr. Mohammad →

Completion is not independent verification.

Python / Google Colab laboratory

K15 · 11 notebook cells · 3 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
# K15 · K15 · Ascon-AEAD128 · lightweight authenticated encryption **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Introduction Apply byte-oriented Ascon-AEAD128 and distinguish encryption, authentication and nonce uniqueness. ## 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 defensive reference; ephemeral keys/files. 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 Apply byte-oriented Ascon-AEAD128 and distinguish encryption, authentication and nonce uniqueness. **Reference procedure (use the matching simulator/WSL tool where named, not an unrelated service):** 1. Select public empty KAT, no fault. Check tag 4427d64b8e1e1451fc445960f0839bb0 against the independent reference. Fixed key and nonce are public test inputs only. 2. Switch to teaching message and enter 15 ASCII bytes, then 16, then 17. Inspect the number of p8 message steps and the mandatory final padded block. 3. Enter nonempty AAD and inspect absorption plus domain separation. Compare ciphertext and tag size; AAD is authenticated but not encrypted into the ciphertext. 4. Modify tag, associated data and nonce separately; each must reject. Try ciphertext modification with a nonempty message. 5. Run python3 ascon_course.py in the supplied toolkit to execute the six independent KATs and the local negative controls. **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
# =====================================================================
# K15 | Code cell 01 | K15 · Ascon-AEAD128 · lightweight authenticated encryption
# 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
# =====================================================================
# K15 | Code cell 02 | K15 · Ascon-AEAD128 · lightweight authenticated encryption
# 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.
# =====================================================================
#!/usr/bin/env python3
"""Byte-oriented educational Ascon-AEAD128, NIST SP 800-232 (2025).
Not hardened or validated for production. No secret inputs or external services.
"""
import hmac, json, os
# Set MASK for the next computation or reference condition.
MASK=(1<<64)-1
# Set IV for the next computation or reference condition.
IV=0x00001000808c0001
# Set RC for the next computation or reference condition.
RC=(0xf0,0xe1,0xd2,0xc3,0xb4,0xa5,0x96,0x87,0x78,0x69,0x5a,0x4b)
# Define the reusable operation rot; keep its logic separate from the trial.
def rot(x,n): return ((x>>n)|(x<<(64-n)))&MASK
# Define the reusable operation perm; keep its logic separate from the trial.
def perm(s,rounds):
    for c in RC[-rounds:]:
        a,b,d,e,f=s; d^=c
        a^=f; f^=e; d^=b
        t=[a,b,d,e,f]; u=[t[i]^((~t[(i+1)%5])&t[(i+2)%5]) for i in range(5)]
        u[1]^=u[0]; u[0]^=u[4]; u[3]^=u[2]; u[2]=(~u[2])&MASK
        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)])]
# Define the reusable operation word; keep its logic separate from the trial.
def word(b): return int.from_bytes(b,'little')
# Define the reusable operation rate; keep its logic separate from the trial.
def rate(s): return s[0].to_bytes(8,'little')+s[1].to_bytes(8,'little')
# Define the reusable operation setrate; keep its logic separate from the trial.
def setrate(s,b): s[0],s[1]=word(b[:8]),word(b[8:])
# Define the reusable operation xor; keep its logic separate from the trial.
def xor(a,b):return bytes(x^y for x,y in zip(a,b))
# Define the reusable operation init; keep its logic separate from the trial.
def init(key,nonce,ad):
    if len(key)!=16 or len(nonce)!=16:raise ValueError('128-bit key and nonce required')
    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
    if ad:
        padded=ad+b'\x01'+b'\0'*((15-len(ad))%16)
        for i in range(0,len(padded),16):setrate(s,xor(rate(s),padded[i:i+16]));perm(s,8)
    s[4]^=1<<63
    return s,k0,k1
# Define the reusable operation finish; keep its logic separate from the trial.
def finish(s,k0,k1):
    s[2]^=k0;s[3]^=k1;perm(s,12);s[3]^=k0;s[4]^=k1
    return s[3].to_bytes(8,'little')+s[4].to_bytes(8,'little')
# Define the reusable operation encrypt; keep its logic separate from the trial.
def encrypt(key,nonce,ad,plain):
    s,k0,k1=init(key,nonce,ad);out=bytearray()
    for i in range(0,len(plain)//16*16,16):
        setrate(s,xor(rate(s),plain[i:i+16]));out.extend(rate(s));perm(s,8)
    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)])
    return bytes(out)+finish(s,k0,k1)
# Define the reusable operation decrypt; keep its logic separate from the trial.
def decrypt(key,nonce,ad,combined):
    if len(combined)<16:raise ValueError('Missing tag')
    c,tag=combined[:-16],combined[-16:];s,k0,k1=init(key,nonce,ad);out=bytearray()
    for i in range(0,len(c)//16*16,16):
        block=c[i:i+16];out.extend(xor(rate(s),block));setrate(s,block);perm(s,8)
    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)
    if not hmac.compare_digest(tag,finish(s,k0,k1)):raise ValueError('Authentication failed')
    return bytes(out)
# Define the reusable operation checks; keep its logic separate from the trial.
def checks():
    # Independent RustCrypto ascon-aead 0.6.0 test vector Count=1 (SP 800-232).
    # https://docs.rs/crate/ascon-aead/0.6.0/source/tests/data/ascon128.txt
    k=bytes(range(16));n=k;expected=bytes.fromhex('4427D64B8E1E1451FC445960F0839BB0');actual=encrypt(k,n,b'',b'')
    results=[{'control':'independent empty-message KAT','pass':actual==expected,'actual':actual.hex(),'expected':expected.hex()}]
    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')]:
        expected=bytes.fromhex(hexout);pt=bytes(range(ml));ad=bytes(range(al));actual=encrypt(k,n,ad,pt)
        results.append({'control':f'independent KAT {count}','pass':actual==expected and decrypt(k,n,ad,expected)==pt,'actual':actual.hex(),'expected':expected.hex()})
    # Fresh key per run, unique nonce for every encryption. Vectors use fixed public inputs only.
    k=os.urandom(16)
    for size in [0,1,15,16,17,31,32,33,128]:
        for alen in [0,1,16,17]:
            nonce=(size*100+alen).to_bytes(16,'little');msg=bytes(range(size));ad=b'A'*alen;ct=encrypt(k,nonce,ad,msg)
            results.append({'control':f'roundtrip-{size}-{alen}','pass':decrypt(k,nonce,ad,ct)==msg})
            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 []):
                try:decrypt(k,nn,aa,cc);ok=False
                except ValueError:ok=True
                results.append({'control':f'reject-{label}-{size}-{alen}','pass':ok})
    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)}
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
# =====================================================================
# K15 | Code cell 03 | K15 · Ascon-AEAD128 · lightweight authenticated encryption
# Purpose: Step 2 · 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=checks()
    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
09Instructions · 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 cd ~/kali-labs python3 ascon_course.py ``` ```bash cd ~/kali-labs mkdir -p ~/psut-security-results python3 ascon_course.py > ~/psut-security-results/K15-evidence.json && cat ~/psut-security-results/K15-evidence.json ``` ```python #!/usr/bin/env python3 """Byte-oriented educational Ascon-AEAD128, NIST SP 800-232 (2025). Not hardened or validated for production. No secret inputs or external services. """ import hmac, json, os MASK=(1<<64)-1 IV=0x00001000808c0001 RC=(0xf0,0xe1,0xd2,0xc3,0xb4,0xa5,0x96,0x87,0x78,0x69,0x5a,0x4b) def rot(x,n): return ((x>>n)|(x<<(64-n)))&MASK def perm(s,rounds): for c in RC[-rounds:]: a,b,d,e,f=s; d^=c a^=f; f^=e; d^=b t=[a,b,d,e,f]; u=[t[i]^((~t[(i+1)%5])&t[(i+2)%5]) for i in range(5)] u[1]^=u[0]; u[0]^=u[4]; u[3]^=u[2]; u[2]=(~u[2])&MASK 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)])] def word(b): return int.from_bytes(b,'little') def rate(s): return s[0].to_bytes(8,'little')+s[1].to_bytes(8,'little') def setrate(s,b): s[0],s[1]=word(b[:8]),word(b[8:]) def xor(a,b):return bytes(x^y for x,y in zip(a,b)) def init(key,nonce,ad): if len(key)!=16 or len(nonce)!=16:raise ValueError('128-bit key and nonce required') 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 if ad: padded=ad+b'\x01'+b'\0'*((15-len(ad))%16) for i in range(0,len(padded),16):setrate(s,xor(rate(s),padded[i:i+16]));perm(s,8) s[4]^=1<<63 return s,k0,k1 def finish(s,k0,k1): s[2]^=k0;s[3]^=k1;perm(s,12);s[3]^=k0;s[4]^=k1 return s[3].to_bytes(8,'little')+s[4].to_bytes(8,'little') def encrypt(key,nonce,ad,plain): s,k0,k1=init(key,nonce,ad);out=bytearray() for i in range(0,len(plain)//16*16,16): setrate(s,xor(rate(s),plain[i:i+16]));out.extend(rate(s));perm(s,8) 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)]) return bytes(out)+finish(s,k0,k1) def decrypt(key,nonce,ad,combined): if len(combined)<16:raise ValueError('Missing tag') c,tag=combined[:-16],combined[-16:];s,k0,k1=init(key,nonce,ad);out=bytearray() for i in range(0,len(c)//16*16,16): block=c[i:i+16];out.extend(xor(rate(s),block));setrate(s,block);perm(s,8) 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) if not hmac.compare_digest(tag,finish(s,k0,k1)):raise ValueError('Authentication failed') return bytes(out) def checks(): # Independent RustCrypto ascon-aead 0.6.0 test vector Count=1 (SP 800-232). # https://docs.rs/crate/ascon-aead/0.6.0/source/tests/data/ascon128.txt k=bytes(range(16));n=k;expected=bytes.fromhex('4427D64B8E1E1451FC445960F0839BB0');actual=encrypt(k,n,b'',b'') results=[{'control':'independent empty-message KAT','pass':actual==expected,'actual':actual.hex(),'expected':expected.hex()}] 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')]: expected=bytes.fromhex(hexout);pt=bytes(range(ml));ad=bytes(range(al));actual=encrypt(k,n,ad,pt) results.append({'control':f'independent KAT {count}','pass':actual==expected and decrypt(k,n,ad,expected)==pt,'actual':actual.hex(),'expected':expected.hex()}) # Fresh key per run, unique nonce for every encryption. Vectors use fixed public inputs only. k=os.urandom(16) for size in [0,1,15,16,17,31,32,33,128]: for alen in [0,1,16,17]: nonce=(size*100+alen).to_bytes(16,'little');msg=bytes(range(size));ad=b'A'*alen;ct=encrypt(k,nonce,ad,msg) results.append({'control':f'roundtrip-{size}-{alen}','pass':decrypt(k,nonce,ad,ct)==msg}) 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 []): try:decrypt(k,nn,aa,cc);ok=False except ValueError:ok=True results.append({'control':f'reject-{label}-{size}-{alen}','pass':ok}) 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)} if __name__=='__main__': r=checks();print(json.dumps(r,indent=2));raise SystemExit(0 if r['pass'] else 1) ```
10Instructions · 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 defensive reference; ephemeral keys/files. Notebook success does not certify external equipment or services.
11Instructions · 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. Switch to teaching message and enter 15 ASCII bytes, then 16, then 17. Inspect the number of p8 message steps and the mandatory final padded block. 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