Skip to main content
PSUT / IoTEngineering learning studio
WORKSPACE
Offline-first portalDr. Mohammad Alja’afreh
Cyber Defense StudioIoT Security and PrivacyExperimentsWorkspaces
ENGINEERING WORKSPACE
Home / Kali security course / K08
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
WSL LABORATORIES / KALI LINUX / SECURITY & PRIVACY
IoT Security and Privacy

K08 · Authenticated encryption & signatures

Ask Dr. Mohammad · K08 →

Practical IoT Security & Privacy · Kali WSL · 40 min

Design experiment & verify evidence →
K08 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Kali & IoT securityK08 · Authenticated encryption & signatures
V19.0 · Contextual AI workspace

Ask your engineering assistants

K08 · 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
K08 · Authenticated encryption & signatures

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.

Readiness checksRevision deckEngineering workspaceRecord evidence
K08 · Academic orientation

Scope and objectives

Scope of the experiment

Compare authenticated encryption with digital signatures and deliberately altered inputs.

The focus of this experiment is to distinguish authenticated encryption from digital signatures. Students then trace nonce, associated data, ciphertext and signature checks, and verify tamper rejection and appropriate key roles. 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

  • Distinguish authenticated encryption from digital signatures.
  • Trace nonce, associated data, ciphertext and signature checks.
  • Verify tamper rejection and appropriate key roles.
  • Identify the configured inputs (Cryptographic primitive; Original message; Associated data (AES-GCM); Receiver modification) 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 distinguish authenticated encryption from digital signatures, trace nonce, associated data, ciphertext and signature checks, and verify tamper rejection and appropriate key roles.

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 tamper rejection and appropriate key roles. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to K09 · Privacy-preserving telemetry.

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.

CONCEPTS / ACTIVE RECALL

Understand the experiment

Scientific architecture · Authenticated encryption and signature verification

AEAD and digital signatures — Plaintext + AAD / input; AEAD / confidentiality and tag; Signature / private signing key; Verify tag and signature / separate checks; Release / only after required checks succeed
Scientific concept map: Plaintext + AAD — Authenticated input; AEAD encrypt — Ciphertext + tag; Signature — Private key signs; Receiver — AEAD check / public key verify; Result — Reject tampering.

Scientific foundations and analytical reasoning

AEAD protects confidentiality and authenticity including associated data; signatures verify origin under a trusted public key; ECDH plus HKDF derives a shared secret.

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 · Confidentiality, origin and key agreement

AEAD encrypts plaintext and authenticates associated data and ciphertext under a symmetric key; associated data is not encrypted. A signature verifies data under a trusted public key and does not encrypt it. ECDH derives a shared secret and HKDF derives purpose-specific keys from key material.

Worked example and engineering interpretation

For AES-GCM with a 16-byte tag, a 32-byte plaintext produces 32 ciphertext bytes plus 16 tag bytes, excluding nonce and metadata. Changing associated data must fail authentication even though the associated data is readable. Use independent public teaching fixtures and never release rejected plaintext.

Engineering principles · additional worked teaching example

AEAD authenticates ciphertext and AAD, encrypts plaintext, and requires nonce discipline. A digital signature is publicly verifiable, not encryption. ECDH establishes shared secret, then HKDF derives purpose-specific key material.

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 K08 · Authenticated encryption & signatures

Verify AEAD, signatures and ECDH/HKDF behavior using positive and negative controls.

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: Verify AEAD, signatures and ECDH/HKDF behavior using positive and negative controls.

  1. Select AES-GCM and no modification. Observe plaintext length, 12-byte IV and 16-byte authentication tag; decrypt the same bytes.
  2. Select ciphertext tampering, then AAD tampering. Both must reject rather than return a modified plaintext.
  3. Switch to ECDSA with no modification, then message modification. Inspect signature length and verification.
  4. Repeat with RSA-PSS. Compare signature length; do not infer runtime performance from size.

Reference check:

Model boundary:

Independent task and submission evidence

2. Select ciphertext tampering, then AAD tampering. Both must reject rather than return a modified plaintext. 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: Cryptographic primitive = AES-GCM; Original message = PSUT fictional telemetry; Associated data (AES-GCM) = demo-device; Receiver modification = none. In the classroom model, Verification = Accepted; Input size = 24 B; Ciphertext + tag size = 40 B. Verification reflects actual cryptographic operations, not a boolean selected by the student. Actual browser cryptography, ephemeral keys, no production secret material. RSA-PSS uses a 32-byte salt in this apparatus.

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 · packet structure

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.

K08 · Authenticated encryption & signatures: packet structureApplication24 BIV12 BCiphertext24 BTag16 BField order; widths are schematic, not byte-proportional.

Step 1 of 4 · Application

Application

Application
24 bytes

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

Recall the concept before revealing its explanation.

0 / 3 revealed
K08 · 01 / 08Why AEAD?Reveal explanation
Engineering explanation

Authenticated encryption protects confidentiality and integrity together.

K08 · 02 / 08What does ECDH/HKDF do?Reveal explanation
Engineering explanation

ECDH establishes a shared secret; HKDF derives usable key material. Authentication is separate.

K08 · 03 / 08Which key-agreement and AEAD prerequisites must be verified?Reveal explanation
Engineering explanation

Inspect all positive and negative crypto checks. Never reuse an AES-GCM nonce with the same key; Ascon is conceptual, not executed by the toolkit.

K08 · 04 / 08What differs between AEAD and a digital signature?Reveal explanation
Engineering reasoning

AEAD provides confidentiality and authenticated integrity with a secret key; signatures provide publicly verifiable authenticity of signed data.

K08 · 05 / 08Why verify decrypted output against the original?Reveal explanation
Engineering reasoning

Correct decryption must reproduce the original bytes; rejection of altered ciphertext is a separate negative check.

K08 · 06 / 08A protected message uses AEAD and signatures. Select every technically valid statement. A. AEAD authenticates ciphertext and associated data under its defined inputs. B. Signature verification requires a trusted verification key. C. Encryption alone necessarily provides sender authenticity. D. ECDH alone verifies the remote identity without authentication.Reveal explanation
Applied scenario

Correct: A. AEAD authenticates ciphertext and associated data under its defined inputs.; B. Signature verification requires a trusted verification key.

K08 · 07 / 08In K08 · Authenticated encryption & signatures, which command or code executes the final documented practical action?Reveal explanation
Implementation recall

cat "$HOME/.psut-kali-security-v14/evidence/K08-CRYPTO.json"

K08 · 08 / 08For K08 · Authenticated encryption & signatures, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance

Run lab.py crypto after verify_kali.sh. Require all JSON checks pass including reference vector and altered-input rejection. Fresh ephemeral keys and nonce values change outputs; compare pass flags rather than ciphertext equality. No broker required.

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

Experimental protocol

Before you run / verification gate

Inspect all positive and negative crypto checks. Never reuse an AES-GCM nonce with the same key; Ascon is conceptual, not executed by the toolkit.

Experimental protocol

Prerequisites
K01; cryptography package
Procedure
Run AES-GCM, RSA-PSS, ECDSA, AES known-answer and ECDH/HKDF checks.
Acceptance
Nine checks pass including tag/AAD rejection, signature rejection, reference tag and shared key agreement. ECDH alone does not authenticate peers.
Evidence
K08-CRYPTO.json; identify properties and constraints of each primitive.
Standards link
Data protection; NIST SP 800-232 comparison
Discussion
Compare AES-GCM with Ascon-AEAD128; explain why DES/3DES are legacy choices and why signing is not encryption.

Run & verify — acceptance checklist

Build verification: Actual AES-GCM, RSA-PSS, ECDSA, ECDH/HKDF controls passed.

Run lab.py crypto after verify_kali.sh. Require all JSON checks pass including reference vector and altered-input rejection. Fresh ephemeral keys and nonce values change outputs; compare pass flags rather than ciphertext equality. No broker required.

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

Draw an AES-GCM packet with nonce, associated data, ciphertext and tag. Identify which fields are confidential and authenticated.

02 · Compare or justify using evidence

Predict outcome of changed ciphertext, changed associated data and a wrong signature-verification key. Explain why signing and encryption are not equivalent.

03 · Architecture

Architecture · Independent work

A packet includes clear device ID as AAD, encrypted temperature and tag. If device ID changes but ciphertext/tag do not, what must verification do? Why?

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

Use the reference configuration (Cryptographic primitive = AES-GCM; Original message = PSUT fictional telemetry; Associated data (AES-GCM) = demo-device; Receiver modification = none), but change Receiver modification = message. The model reports Verification = 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 · K08-02

The reference model reports Verification: Accepted. Under Receiver modification = message 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 · K08-03

For Receiver modification = ciphertext, the model supplies this excerpt from Cryptographic operation: Field · Actual computed value IV · b9cefc3b6a9ce5317713b7f9 AAD · demo-device Original ciphertext+tag · 7cc20ea2fec0feef6c5359eda3d88088d78851729fb2c17ae262219ec371e58d1c5c900fcf9ab433 Received ciphertext+tag · 7cc20ea2fec0feef6c5359eda3d88088d78851729fb2c17ae262219ec371e58d1c5c900fcf9ab432 Tag bytes · 16 Count rows whose Actual computed value value is exactly “b9cefc3b6a9ce5317713b7f9”, and identify the displayed row numbers. Explain what the count describes.

Advanced · Reverse reasoning

Independent theoretical exercise · K08-04

An observation is Verification = Rejected. Candidate A uses Cryptographic primitive = AES-GCM; Original message = PSUT fictional telemetry; Associated data (AES-GCM) = demo-device; Receiver modification = none. Candidate B changes the listed settings (Receiver modification = ciphertext) 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 · K08-05

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

Challenging · Design a controlled verification

Independent theoretical exercise · K08-06

Design a controlled comparison for K08 · Authenticated encryption & signatures using reference Cryptographic primitive = AES-GCM; Original message = PSUT fictional telemetry; Associated data (AES-GCM) = demo-device; Receiver modification = none and test Receiver modification = message. Specify the changed setting(s), measured metric Verification, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

Step-by-step experimental procedure

Compare authenticated encryption with digital signatures and deliberately altered inputs.

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.

Cryptographic primitiveAES-GCM
Original messagePSUT fictional telemetry
Associated data (AES-GCM)demo-device
Receiver modificationnone

2 · Perform the investigation in order

  1. Select AES-GCM and no modification. Observe plaintext length, 12-byte IV and 16-byte authentication tag; decrypt the same bytes.
  2. Select ciphertext tampering, then AAD tampering. Both must reject rather than return a modified plaintext.
  3. Switch to ECDSA with no modification, then message modification. Inspect signature length and verification.
  4. Repeat with RSA-PSS. Compare signature length; do not infer runtime performance from size.
  5. Run lab.py crypto locally; verify its AES-GCM known-answer and ECDH/HKDF agreement checks independently.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
AES-GCM originalUse reference inputs aboveVerification: AcceptedRecord actual result
AES-GCM modified tagReceiver modification = ciphertextVerification: RejectedRecord actual result
AES-GCM modified AADReceiver modification = AADVerification: RejectedRecord actual result
ECDSA modified messageCryptographic primitive = ECDSA; Receiver modification = messageVerification: RejectedRecord actual result
RSA-PSS originalCryptographic primitive = RSA-PSSVerification: AcceptedRecord actual result

4 · Analyze and report

Explain which primitive provides confidentiality and which provides public verification.

Required evidence: Algorithm-by-algorithm positive and negative evidence.

Model boundary: Actual browser cryptography, ephemeral keys, no production secret material. RSA-PSS uses a 32-byte salt in this apparatus.

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
AES-GCM originalUse reference inputs aboveRecord actual outcome and units
AES-GCM modified tagReceiver modification = ciphertextRecord actual outcome and units
AES-GCM modified AADReceiver modification = AADRecord actual outcome and units
ECDSA modified messageCryptographic primitive = ECDSA; Receiver modification = messageRecord 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 defensive function; ephemeral evidence directory. Validated locally in a fresh Jupyter kernel. Download, then upload to Google Colab.

Download NotebookOpen Google ColabAll Python notebooks
K08 / Kali · Python cryptography40 min

Authenticated encryption & signatures

Kali terminal C · working directory
Kali (Bash)
cd ~/kali-labs
bash verify_kali.sh
✓ Expected: Toolkit directory is selected and all dependency checks pass. Do not proceed if any check fails.

Objective: Execute AES-GCM, RSA-PSS and ECDSA using real cryptographic libraries.

Verify altered ciphertext/AAD and altered signed messages are rejected.

ACTION 01 / 02
Kali terminal C
python3 lab.py crypto
✓ Expected: The JSON report records successful AES-GCM decryption and RSA/ECDSA signature verification, plus altered-input rejection.
ACTION 02 / 02
Kali terminal C
cat "$HOME/.psut-kali-security-v14/evidence/K08-CRYPTO.json"
✓ Expected: The saved JSON report prints individual check outcomes. Review pass/fail rather than assuming all tests succeeded.

Experimental notebook

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

Method and implementation

Review the implementation after attempting the practical steps.

Cryptographic properties · method and source

AES-GCM authenticates ciphertext and associated data. Use a fresh 96-bit nonce for each encryption under a given key. RSA-PSS and ECDSA verify signatures against a public key; they do not encrypt the message. The lab uses fresh ephemeral keys.

Inspect the actual implementation below. Full file: lab.py.

PYTHON · Source code
def crypto():
    from cryptography.hazmat.primitives.ciphers.aead import AESGCM
    from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa
    from cryptography.hazmat.primitives import hashes
    from cryptography.hazmat.primitives.kdf.hkdf import HKDF
    from cryptography.exceptions import InvalidTag,InvalidSignature
    a=b'PSUT fictional telemetry'; b=a+b' changed'; aad=b'demo-device'; key=AESGCM.generate_key(bit_length=128);g=AESGCM(key);nonce=secrets.token_bytes(12);ct=g.encrypt(nonce,a,aad);tests=[check('AES-GCM round trip',g.decrypt(nonce,ct,aad)==a,'original verified')]
    for name,modified,associated in [('Altered ciphertext',ct[:-1]+bytes([ct[-1]^1]),aad),('Altered AAD',ct,b'wrong-device')]:
        try:g.decrypt(nonce,modified,associated);ok=False
        except InvalidTag:ok=True
        tests.append(check(name,ok,'authentication rejection expected'))
    e=ec.generate_private_key(ec.SECP256R1());r=rsa.generate_private_key(public_exponent=65537,key_size=2048);pss=padding.PSS(mgf=padding.MGF1(hashes.SHA256()),salt_length=padding.PSS.MAX_LENGTH)
    for name,priv,args in [('ECDSA P-256',e,[ec.ECDSA(hashes.SHA256())]),('RSA-PSS',r,[pss,hashes.SHA256()])]:
        sig=priv.sign(a,*args);priv.public_key().verify(sig,a,*args);tests.append(check(name+' original',True,'signature verifies'))
        try:priv.public_key().verify(sig,b,*args);ok=False
        except InvalidSignature:ok=True
        tests.append(check(name+' altered',ok,'signature rejected'))
    # NIST GCM zero-key/IV, empty plaintext reference case; never use this key outside a KAT.
    kat=AESGCM(bytes(16)).encrypt(bytes(12),b'',None).hex()
    tests.append(check('AES-GCM known answer',kat=='58e2fccefa7e3061367f1d57a4e7455a','fixed reference tag'))
    alice=ec.generate_private_key(ec.SECP256R1());bob=ec.generate_private_key(ec.SECP256R1())
    def derive(secret):return HKDF(algorithm=hashes.SHA256(),length=16,salt=None,info=b'PSUT teaching ECDH').derive(secret)
    tests.append(check('ECDH/HKDF agreement',derive(alice.exchange(ec.ECDH(),bob.public_key()))==derive(bob.exchange(ec.ECDH(),alice.public_key())),'agreement only; peer authentication still required'))
    return save('K08-CRYPTO',tests)

Lightweight cryptography: compare AES-GCM with the standardized Ascon-AEAD128; both provide authenticated encryption, but use different designs. Ascon here is conceptual, not an executable implementation. Review official reference implementation and known-answer tests. DES/3DES are historical, not recommended for new protection. Never use the fixed key/nonce known-answer test as a real encryption configuration.

Verification and notebook

Expected observation / verification

Nine checks pass including tag/AAD rejection, signature rejection, reference tag and shared key agreement. ECDH alone does not authenticate peers.

Engineering discussion

Explain what a signature provides that symmetric encryption alone does not.

Python / Google Colab laboratory

K08 · 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
# K08 · K08 · Authenticated encryption & signatures **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Introduction Verify AEAD, signatures and ECDH/HKDF behavior using positive and negative controls. ## 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 defensive function; ephemeral evidence directory. 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 Verify AEAD, signatures and ECDH/HKDF behavior using positive and negative controls. **Reference procedure (use the matching simulator/WSL tool where named, not an unrelated service):** 1. Select AES-GCM and no modification. Observe plaintext length, 12-byte IV and 16-byte authentication tag; decrypt the same bytes. 2. Select ciphertext tampering, then AAD tampering. Both must reject rather than return a modified plaintext. 3. Switch to ECDSA with no modification, then message modification. Inspect signature length and verification. 4. Repeat with RSA-PSS. Compare signature length; do not infer runtime performance from size. 5. Run lab.py crypto locally; verify its AES-GCM known-answer and ECDH/HKDF agreement checks independently. **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
# =====================================================================
# K08 | Code cell 01 | K08 · Authenticated encryption & signatures
# 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
# =====================================================================
# K08 | Code cell 02 | K08 · Authenticated encryption & signatures
# 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 json, secrets, time

from pathlib import Path

# Set HOME for the next computation or reference condition.
HOME=Path.home()/'.psut-kali-security-v14'

# Define the reusable operation save; keep its logic separate from the trial.
def save(name, tests):
    report={'schema':'psut-kali-v14','experiment':name,'source':'local-execution-self-reported','utc':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()),'checks':tests}
    out=HOME/'evidence'; out.mkdir(parents=True,exist_ok=True,mode=0o700)
    (out/(name+'.json')).write_text(json.dumps(report,indent=2)+'\n')
    print(json.dumps(report,indent=2)); return all(x['pass'] for x in tests)

# Define the reusable operation check; keep its logic separate from the trial.
def check(name, ok, observation): return {'name':name,'pass':bool(ok),'observation':str(observation)}

# Define the reusable operation crypto; keep its logic separate from the trial.
def crypto():
    from cryptography.hazmat.primitives.ciphers.aead import AESGCM
    from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa
    from cryptography.hazmat.primitives import hashes
    from cryptography.hazmat.primitives.kdf.hkdf import HKDF
    from cryptography.exceptions import InvalidTag,InvalidSignature
    a=b'PSUT fictional telemetry'; b=a+b' changed'; aad=b'demo-device'; key=AESGCM.generate_key(bit_length=128);g=AESGCM(key);nonce=secrets.token_bytes(12);ct=g.encrypt(nonce,a,aad);tests=[check('AES-GCM round trip',g.decrypt(nonce,ct,aad)==a,'original verified')]
    for name,modified,associated in [('Altered ciphertext',ct[:-1]+bytes([ct[-1]^1]),aad),('Altered AAD',ct,b'wrong-device')]:
        try:g.decrypt(nonce,modified,associated);ok=False
        except InvalidTag:ok=True
        tests.append(check(name,ok,'authentication rejection expected'))
    e=ec.generate_private_key(ec.SECP256R1());r=rsa.generate_private_key(public_exponent=65537,key_size=2048);pss=padding.PSS(mgf=padding.MGF1(hashes.SHA256()),salt_length=padding.PSS.MAX_LENGTH)
    for name,priv,args in [('ECDSA P-256',e,[ec.ECDSA(hashes.SHA256())]),('RSA-PSS',r,[pss,hashes.SHA256()])]:
        sig=priv.sign(a,*args);priv.public_key().verify(sig,a,*args);tests.append(check(name+' original',True,'signature verifies'))
        try:priv.public_key().verify(sig,b,*args);ok=False
        except InvalidSignature:ok=True
        tests.append(check(name+' altered',ok,'signature rejected'))
    # NIST GCM zero-key/IV, empty plaintext reference case; never use this key outside a KAT.
    kat=AESGCM(bytes(16)).encrypt(bytes(12),b'',None).hex()
    tests.append(check('AES-GCM known answer',kat=='58e2fccefa7e3061367f1d57a4e7455a','fixed reference tag'))
    alice=ec.generate_private_key(ec.SECP256R1());bob=ec.generate_private_key(ec.SECP256R1())
    def derive(secret):return HKDF(algorithm=hashes.SHA256(),length=16,salt=None,info=b'PSUT teaching ECDH').derive(secret)
    tests.append(check('ECDH/HKDF agreement',derive(alice.exchange(ec.ECDH(),bob.public_key()))==derive(bob.exchange(ec.ECDH(),alice.public_key())),'agreement only; peer authentication still required'))
    return save('K08-CRYPTO',tests)
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
# =====================================================================
# K08 | Code cell 03 | K08 · Authenticated encryption & signatures
# 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
# Limit resource lifetime to this block so files, sockets or temporary state are cleaned up.
with tempfile.TemporaryDirectory() as d:
    HOME=Path(d)
    assert crypto()
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 python3 lab.py crypto ``` ```python def crypto(): from cryptography.hazmat.primitives.ciphers.aead import AESGCM from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.hkdf import HKDF from cryptography.exceptions import InvalidTag,InvalidSignature a=b'PSUT fictional telemetry'; b=a+b' changed'; aad=b'demo-device'; key=AESGCM.generate_key(bit_length=128);g=AESGCM(key);nonce=secrets.token_bytes(12);ct=g.encrypt(nonce,a,aad);tests=[check('AES-GCM round trip',g.decrypt(nonce,ct,aad)==a,'original verified')] for name,modified,associated in [('Altered ciphertext',ct[:-1]+bytes([ct[-1]^1]),aad),('Altered AAD',ct,b'wrong-device')]: try:g.decrypt(nonce,modified,associated);ok=False except InvalidTag:ok=True tests.append(check(name,ok,'authentication rejection expected')) e=ec.generate_private_key(ec.SECP256R1());r=rsa.generate_private_key(public_exponent=65537,key_size=2048);pss=padding.PSS(mgf=padding.MGF1(hashes.SHA256()),salt_length=padding.PSS.MAX_LENGTH) for name,priv,args in [('ECDSA P-256',e,[ec.ECDSA(hashes.SHA256())]),('RSA-PSS',r,[pss,hashes.SHA256()])]: sig=priv.sign(a,*args);priv.public_key().verify(sig,a,*args);tests.append(check(name+' original',True,'signature verifies')) try:priv.public_key().verify(sig,b,*args);ok=False except InvalidSignature:ok=True tests.append(check(name+' altered',ok,'signature rejected')) # NIST GCM zero-key/IV, empty plaintext reference case; never use this key outside a KAT. kat=AESGCM(bytes(16)).encrypt(bytes(12),b'',None).hex() tests.append(check('AES-GCM known answer',kat=='58e2fccefa7e3061367f1d57a4e7455a','fixed reference tag')) alice=ec.generate_private_key(ec.SECP256R1());bob=ec.generate_private_key(ec.SECP256R1()) def derive(secret):return HKDF(algorithm=hashes.SHA256(),length=16,salt=None,info=b'PSUT teaching ECDH').derive(secret) tests.append(check('ECDH/HKDF agreement',derive(alice.exchange(ec.ECDH(),bob.public_key()))==derive(bob.exchange(ec.ECDH(),alice.public_key())),'agreement only; peer authentication still required')) return save('K08-CRYPTO',tests) ```
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 defensive function; ephemeral evidence directory. 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. Select ciphertext tampering, then AAD tampering. Both must reject rather than return a modified plaintext. 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