17  Lab: Encryption

Hands-On Cryptography Labs for IoT Message Protection and Release Evidence

cryptography
encryption

17.1 Start With One Protected Message

Picture a learner holding one telemetry packet: payload, device id, timestamp, nonce, and the rule that will act on it. The lab has a simple job before it grows into code. Protect that one packet, break it on purpose, and record evidence that proves the receiver rejects tamper, wrong context, stale replay, and secret leakage.

Use the rest of the chapter as a build path. Boundary first, authenticated protection second, negative tests third, and only then a release decision that a reviewer can trust without seeing raw keys.

In 60 Seconds

Encryption labs are not about copying a long code sample. A strong lab asks learners to protect one IoT message, prove what security property was achieved, break the design on purpose, and record evidence that a reviewer can trust.

17.2 Learning Objectives

By the end of this chapter, you will be able to:

  • Plan a small encryption lab around a clear data boundary, threat, and success condition.
  • Use authenticated protection as the default pattern for IoT message confidentiality and integrity.
  • Separate lab-only demonstrations from controls that could support a release decision.
  • Build evidence for nonce handling, key lifecycle, replay rejection, and failure behavior.
  • Review lab output without exposing secrets, private keys, raw tokens, or recovery material.

17.3 Prerequisites

Before starting these labs, review:

17.4 Lab Quality Rules

The old version of a lab often starts with a board, a button, and a large code block. That can be useful for exploration, but it can also hide the lesson. A better encryption lab starts with a security question.

Boundary

17.4.0.1 What is protected?

Name the payload, metadata, sender, receiver, and trust boundary before choosing an algorithm.

Mechanism

17.4.0.2 How is it protected?

Use an approved authenticated protection pattern, then record the nonce, tag, AAD, and failure behavior.

Keys

17.4.0.3 How are keys handled?

Show key source, scope, rotation trigger, and storage boundary without exposing the secret value.

Negative Tests

17.4.0.4 What fails safely?

Replay, tamper, wrong key, wrong context, and stale sequence tests must reject before plaintext is trusted.

Encryption lab practice loop from boundary map to protection, negative test, evidence, and release decision.
A useful encryption lab loops from boundary mapping to protection, failure testing, and release evidence.

17.5 Authenticated Protection Is the Lab Baseline

A common lab mistake is to think that encrypting data makes it safe. Encryption hides contents, but by itself it does not prove that a packet was not altered in transit. A receiver can decrypt modified ciphertext into some output and still have no trustworthy signal that the message was tampered with.

The modern baseline is authenticated encryption with associated data (AEAD). Modes and constructions such as AES-GCM and ChaCha20-Poly1305 keep the payload confidential and produce an authentication tag that detects modification. If a lab uses plain encryption without authentication, it is only testing half the requirement.

A complete lab proves both the happy path and the rejection path. The receiver should accept the original packet, then reject a packet with one altered ciphertext byte, one altered associated-data field, the wrong key, and a repeated or malformed nonce where the design forbids it. The record should name the packet fields, the tag check, and the receiver decision before any plaintext is trusted.

The same record should state what remains outside confidentiality. Associated data can be visible and still authenticated, which is useful for routing, device identity, command class, or topic selection, but it is not private. If a field is sensitive, put it inside the encrypted plaintext instead of in the associated-data header.

AEAD Intuition

Encryption is a sealed envelope. AEAD is a sealed envelope with a tamper-evident seal. If anyone opens or alters it, the receiver rejects the whole packet instead of trusting the contents.

Authenticated Protection Check

17.6 Nonce and Key Lifecycle Rules

An AEAD operation takes a key, a unique nonce, plaintext, and optional associated data. It returns ciphertext plus a tag:

ciphertext, tag = AEAD_encrypt(key, nonce, plaintext, associated_data)
tag             = authentication tag verified before plaintext is trusted
nonce           = unique for every encryption under the same key
associated_data = authenticated but not encrypted context, such as a header

Treat the nonce rule as an operational requirement, not a footnote. A random nonce needs enough entropy and monitoring for collision assumptions. A counter nonce needs durable state so it never rolls back after reboot, factory reset, crash recovery, or duplicate provisioning. If the design cannot prove uniqueness, use a protocol or mode that reduces misuse risk rather than hoping reset behavior is always correct.

Record who owns the key lifecycle. Lab evidence should say how the key is generated, where it is stored, what scope it covers, when it rotates or revokes, and what test proves an old or wrong key fails closed. Do not prove success by printing the secret.

17.6.0.1 Verify the Tag First

On decrypt, if the tag check fails, reject the entire message. Never process or return partially decrypted plaintext.

17.6.0.2 Never Reuse a Nonce

A nonce is public but must be unique under the same key. Reusing a key/nonce pair in GCM is catastrophic for confidentiality and forgery resistance.

17.6.0.3 Match Cipher to Device

AES-GCM is fast where AES hardware acceleration exists. ChaCha20-Poly1305 is often a better software default on devices without AES acceleration.

Nonce Discipline Check

17.7 Failure-Oriented Review

AEAD became the default because real systems were broken when encryption lacked integrity protection. A padding oracle is dangerous because it turns an error message into a side channel. The attacker does not need the key; they need a way to submit modified ciphertext and learn whether the receiver considered the padding valid. Repeating that query can reveal plaintext one byte at a time.

The fix is not to hide a nicer error string while still processing modified plaintext. The fix is to authenticate the ciphertext first and reject the whole packet before decryption output is exposed. AEAD packages that rule into the primitive: the tag covers the ciphertext and any associated data, and the receiver verifies the tag before releasing plaintext to application logic.

This is why “decrypt succeeded once” is weak evidence. Stronger evidence is a decision table: original packet accepted, changed tag rejected, changed ciphertext rejected, changed associated data rejected, wrong key rejected, replay handled, and the application receives no plaintext when any check fails. That table proves fail-closed behavior, not just cryptographic API usage.

17.7.0.1 Padding Oracle

Unauthenticated CBC mode can be broken if an attacker can distinguish valid padding from invalid padding. AEAD rejects modified ciphertext before that kind of signal is exposed.

17.7.0.2 Encrypt Then Authenticate

The safe generic composition authenticates ciphertext before trusting decryption output. AEAD modes bake this ordering into one interface.

17.7.0.3 Constant-Time Tag Check

Use the library’s tag verification path. A byte-by-byte early-exit comparison leaks how many tag bytes matched.

17.7.0.4 Nonce Management at Scale

Counters can guarantee uniqueness when state is durable. Where reuse cannot be ruled out, a nonce-misuse-resistant mode such as AES-GCM-SIV can limit damage.

Failure Mode Check

17.8 Lab 1: Protect One Telemetry Message

This lab turns one ordinary IoT message into a security exercise. The goal is not to implement a complete product. The goal is to prove that one message can cross a boundary without leaking plaintext or accepting tampering.

Scenario: A field device sends a temperature reading to a gateway. The payload should remain confidential, the gateway should detect tampering, and the receiver should reject stale or replayed packets.

17.8.1 Lab Setup

Use any safe local language or simulator that supports a vetted cryptographic library. Do not write a cipher from scratch. The lab notebook should describe:

  • Plaintext fields: payload value, sender identifier, sequence value, and timestamp or counter.
  • Associated data: routing or device context that must be authenticated but does not need encryption.
  • Protection mechanism: an authenticated encryption mode or secure-channel API.
  • Nonce rule: each protected message uses a unique nonce under the same key.
  • Output format: nonce, ciphertext, authentication tag, and authenticated context.
  • Reject behavior: no plaintext is used until authentication succeeds.

17.8.2 Expected Evidence

Evidence Item
What to Capture
Pass Signal
Do Not Capture
Boundary map
Message fields, sender, receiver, and authenticated metadata.
Reviewer can tell exactly what is confidential and what is authenticated.
Secret keys, private tokens, or device recovery values.
Protected packet
Nonce identifier, ciphertext length, tag length, and AAD name.
Same plaintext produces different protected packets when nonce changes.
Raw key bytes or unredacted credential material.
Receiver decision
Accepted packet trace and rejected packet trace.
Receiver authenticates before releasing plaintext to application logic.
Debug logs that print decrypted secrets on failure paths.

17.8.3 Practice Tasks

Run it: Before you protect the telemetry message by hand, watch the block cipher that sits underneath AES-GCM. Choose an AES key size and a plaintext example, then press Play or Step and drag the Timeline checkpoint so you can compare the before and after state panels through each SubBytes, ShiftRows, MixColumns, and AddRoundKey operation of a round. Use what the animation shows to justify, in your packet record, why the ciphertext hides the payload value, and keep the nonce, tag, and AAD reasoning for the authenticated-encryption steps you run below.

  1. Draw the packet boundary before running the lab.
  2. Protect one message using authenticated encryption or a secure-channel API.
  3. Record the nonce, ciphertext length, authentication tag length, and AAD fields.
  4. Repeat with the same plaintext and a different nonce.
  5. Confirm that the protected output changes.
  6. Tamper with one byte and confirm that the receiver rejects the packet.
  7. Repeat with a wrong context value and confirm that AAD binding works.
Lab Shortcut That Must Not Ship

A teaching lab may use sample messages and temporary keys. A release candidate must not rely on source-embedded secrets, unauthenticated encryption, reused nonces, or “accept anyway” fallback behavior. Treat every lab artifact as evidence, not production configuration.

17.9 Lab 2: Bind Metadata with Associated Data

Encryption protects payload bytes. IoT messages also carry metadata: device identity, route, topic, command class, firmware channel, or sequence value. Some metadata must stay visible for routing, but it still needs integrity protection.

Protected packet evidence with authenticated context, nonce, ciphertext, tag, and receiver decision.
The receiver should authenticate visible context and encrypted payload before trusting the message.

17.9.1 Associated Data Checklist

Use associated data for fields that are visible but must not be silently changed:

  • Device identifier or enrollment alias.
  • Message type such as telemetry, command, update, or diagnostic.
  • Firmware channel or policy version.
  • Sequence number, counter, or freshness marker.
  • Routing topic or gateway context when the receiver depends on it.

17.9.2 Negative Tests

Run these tests even if the happy path already works:

Tamper

17.9.2.1 Change ciphertext

Flip one ciphertext bit. The receiver rejects the packet and does not release plaintext.

Context

17.9.2.2 Change AAD

Change the device id or topic. Authentication fails because visible metadata is bound to the tag.

Replay

17.9.2.3 Repeat old packet

Replay an accepted packet. The freshness check rejects the old sequence or timestamp.

Wrong Key

17.9.2.4 Use wrong scope

Try a key from another device, group, or session. The receiver rejects the packet.

17.10 Lab 3: Key Establishment Evidence

This lab verifies that a session key is created, scoped, and replaced without exposing it. Learners should not prove success by printing the secret. They should prove success through observable behavior.

17.10.1 What to Record

Run it: Instead of describing key establishment from memory, run the comparison animation and switch it to Hybrid mode, which is how real sessions actually agree on a key: an asymmetric step establishes a fresh symmetric key that then protects the traffic. Choose a scenario such as Provisioning or Field command, step through with Play or Step, and watch which party holds which key and where a new session key is derived. Record the establishment profile, the participating peer identities, and the evidence that a new session yields new traffic keys from what the animation shows, and keep the no-secret-leakage rule on your notebook.

  • Which peer identities participated in the exchange.
  • Which approved key establishment or secure-channel profile was used.
  • Which context values were bound into the derivation.
  • Whether a new session produces new traffic keys.
  • How failure is handled when the peer identity, transcript, or context changes.

17.10.2 What Not to Record

  • Private keys.
  • Raw shared secrets.
  • Recovery secrets.
  • Long-term device credentials.
  • Complete unredacted key material in screenshots or logs.
Evidence Without Secret Leakage

Use fingerprints, key identifiers, transcript hashes, decision logs, and pass/fail traces. Those artifacts let a reviewer verify behavior without turning the lab notebook into a credential leak.

17.11 Lab 4: Freshness and Replay Rejection

Freshness is easy to ignore because encryption can still decrypt an old packet. A correct lab shows that the receiver treats stale packets as unsafe even when the authentication tag is valid.

1. Send baseline

Record one accepted protected message with sequence or freshness evidence.

2. Replay exact bytes

Resend the same protected packet without changing the sequence value.

3. Verify rejection

Confirm the receiver rejects it as stale before application logic acts.

4. Rotate context

Start a new session and confirm old traffic is not accepted under the new context.

17.11.1 Freshness Evidence

Good freshness evidence says more than “packet failed.” Record:

  • Last accepted sequence value or receiver freshness window.
  • Rejection reason for duplicate, stale, or out-of-window packets.
  • Whether the application was prevented from acting on rejected data.
  • How the receiver recovers after a restart or resynchronization event.

17.12 Lab 5: Lab-to-Release Review

The final lab turns technical results into a release decision. A reviewer should be able to follow the chain from design intent to test evidence without rerunning every command.

Lab-to-release evidence gates for boundary, mechanism, key lifecycle, negative tests, operations, and audit.
Lab evidence becomes useful when each release gate has a clear pass or block decision.
Gate
Question
Pass Evidence
Blocker
Boundary
Do we know exactly what is protected?
Data-flow map, packet fields, and trust boundary are named.
Unclear ownership of payload, metadata, or receiver decision.
Mechanism
Does the mechanism provide the required properties?
Authenticated protection and approved algorithm profile are documented.
Confidentiality-only encryption where tamper detection is required.
Lifecycle
Can keys be created, scoped, renewed, and retired?
Key identifiers, scope, derivation context, and rotation trigger are recorded.
One shared secret reused across unrelated devices or sessions.
Failure
Do unsafe packets fail closed?
Tamper, wrong context, wrong key, replay, and stale tests reject safely.
Fallback accepts plaintext or bypasses tag validation.
Audit
Can evidence be shared safely?
Logs show decisions, identifiers, and fingerprints without secrets.
Notebook contains keys, tokens, private material, or decrypted sensitive values.

17.13 Suggested Lab Sequence

Use this sequence when teaching or reviewing the chapter:

1. Map

Define payload, metadata, sender, receiver, and threat.

2. Protect

Use authenticated protection and record packet shape.

3. Bind

Add associated data for visible metadata that must not change.

4. Break

Run tamper, wrong-key, wrong-context, and replay tests.

5. Review

Convert traces into pass/block evidence without exposing secrets.

17.14 Common Pitfalls

Encryption alone does not prove authenticity, freshness, or correct receiver behavior. Every lab should include negative tests and a decision log.

Logs that reveal keys or shared secrets are not good evidence. Use fingerprints, key ids, and pass/fail traces instead.

If a receiver trusts a topic, device id, command type, or policy version, bind it as associated data or protect it in the secure channel.

Nonce uniqueness is part of the security design. A lab must include evidence that protected messages under the same key use distinct nonces or a safe deterministic construction.

Many weak labs reject a tampered packet but still log plaintext or trigger downstream actions. Verify that rejected packets stop before application behavior.

17.15 From Interactive Tools to Lab Evidence

Interactive cryptography tools let learners see how keys, nonces, hashes, signatures, and handshakes behave. That is useful learning evidence. A lab that follows tool exploration must go further: it must replace the tool’s assumptions with approved algorithms, measured behavior, and negative tests before the result can support a release decision.

Worked Example: Translating a Keyspace Slider

A learner uses a keyspace calculator and concludes that “a long key is enough.” That is a useful starting point, but the release question is broader: what exactly protects each message, and how does the system fail when the protection is wrong?

Tool observation: Long symmetric keys resist naive exhaustive search.

Missing assumptions:

  • Which mode provides authenticated encryption?
  • How are nonces generated and stored?
  • Can any component reuse a key/nonce pair after restart?
  • Are messages bound to device identity, purpose, and sequence?
  • Does the receiver reject modified ciphertext and stale messages?

Release evidence required:

  • Approved AEAD mode and parameter policy.
  • Test vectors for encryption and decryption.
  • Negative tests for tampered tags, wrong keys, repeated nonces, and replay.
  • Key provisioning, rotation, revocation, and incident-response owner.

The slider taught one idea: keyspace grows quickly. It did not prove authenticated encryption, replay resistance, identity binding, storage safety, or lifecycle control.

For each tool-assisted decision, write a short review record:

  1. Question: What decision are we making?
  2. Tool lesson: What concept did the visualizer or worksheet clarify?
  3. Assumptions: What did the tool simplify?
  4. Standard: Which approved algorithm, mode, protocol, or transition rule applies?
  5. Implementation: Which library/API setting enforces it?
  6. Negative tests: Which bad inputs must be rejected?
  7. Lifecycle owner: Who rotates, revokes, audits, and responds after release?

17.16 Knowledge Check

Encryption Lab Review
Label the Diagram

Code Challenge

Order the Steps

Match the Concepts

17.17 Release Evidence Checklist

  • Boundary map names payload, metadata, sender, receiver, and trust boundary.
  • Mechanism provides the properties the scenario requires.
  • Nonce or sequence rule is documented and tested.
  • Associated data binds visible metadata that the receiver trusts.
  • Key source, scope, and renewal trigger are recorded without exposing secrets.
  • Tamper, wrong key, wrong context, stale packet, and replay tests fail closed.
  • Receiver does not release plaintext or trigger actions after authentication failure.
  • Evidence uses fingerprints, identifiers, and decision logs instead of raw secrets.
  • Lab-only simplifications are explicitly labeled as not release controls.
  • Reviewer can make a clear pass or block decision from the record.

17.18 Key Concepts

  • Authenticated protection: Encryption plus integrity and authenticity verification, typically through AEAD or a secure-channel API.
  • Associated data: Context that remains visible but is authenticated with the protected message.
  • Nonce uniqueness: A rule that prevents repeated encryption inputs under the same key and protection mode.
  • Freshness: Evidence that stale or repeated packets are rejected.
  • Audit-safe evidence: Logs, screenshots, and records that prove behavior without exposing secrets.

17.20 What’s Next

If you want to… Read this
Test the evidence workflow with a capstone review Encryption Labs, Quiz, and Review
Practice with puzzle-style activities Encryption Games
Revisit secure channel behavior TLS and DTLS

Continue to Encryption Labs, Quiz, and Review to turn lab evidence into a final review decision.

17.21 Summary

Encryption labs connect cryptographic concepts to implementation evidence: keys are generated, channels are negotiated, messages are protected, tampering is rejected, and failures are visible.

17.22 Key Takeaway

A useful encryption lab tests negative cases. Verify that wrong keys, altered messages, expired certificates, and unauthorized peers fail closed instead of only proving that the happy path works.