Skip to main content
IoT
PSUT Engineering StudioPrincess Sumaya University for Technology
Student Edition
Connected Networks StudioNetworking and CommunicationExperimentsWorkspaces
Home / IoT Security and Privacy / Cryptography Engineering
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
CRYPTOGRAPHY ENGINEERING · CR79 · TLS AND HTTPS
IoT Security and Privacy

TLS record framing and AEAD overhead

TLS 1.3 outer record header has 5 bytes; encrypted content contains plaintext, inner content type and optional padding, plus AEAD tag (16 bytes in this example).

CR79 · Laboratory mentorAsk about the current operation and its intermediate values.

Related course access: Networking and Communication — same laboratory, notebook and completion record.

CR79 · Academic orientation

Scope and objectives

Scope of the experiment

The record layer frames data and protects it with negotiated keys. AEAD combines encryption and authentication and binds associated header/context data.

The focus of this experiment is to calculate record header, inner content type, padding and AEAD tag length. Students then trace record protection and authenticate associated header data, and verify local decryption and rejection of modified fields. The Concepts view explains the operation before the practical work; the Simulation view is used to examine reference and changed inputs, not to substitute for actual measurements.

Learning objectives

  • Calculate record header, inner content type, padding and AEAD tag length.
  • Trace record protection and authenticate associated header data.
  • Verify local decryption and rejection of modified fields.
  • Record the relevant inputs, intermediate states and final verification result before changing the reference configuration.
  • Compare the reference calculation or decision with an independent implementation or authorized observation; state any discrepancy and the applicable model boundary.

Expected learning outcomes

On completion, students can calculate record header, inner content type, padding and AEAD tag length, trace record protection and authenticate associated header data, and verify local decryption and rejection of modified fields.

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 local decryption and rejection of modified fields. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to Verified local TLS 1.2/1.3 and hostname failure.

Environment and experimental methodology

A standard browser and the experiment-specific Python implementation or Colab notebook. Where the practical uses a protocol model, model results are distinguished from actual local cryptographic operations.

Begin with a manual prediction, record the baseline, change one independent condition at a time, and compare the resulting trace or measurements with the original prediction. Record observations and uncertainty separately from reference values. Follow the experiment’s specific procedure, safety limits, and acceptance checks.

01 · Experiment overview

CR79 · TLS record framing and AEAD overhead

TLS 1.3 outer record header has 5 bytes; encrypted content contains plaintext, inner content type and optional padding, plus AEAD tag (16 bytes in this example). Outer content type is application_data for encrypted records.

Learning objectives

Trace the named operation, reproduce intermediate values, verify the result and explain the consequences of a controlled change.

Prerequisites

Before starting

Environment: standard computer, browser and Python/WSL.

Simulation: Recorded, verified Python scenarios; use Python for arbitrary inputs

Technical scope: Length model only; no ciphertext generated.

Complete the six stages in order. Use the same experiment inputs when comparing manual, browser and Python results.

02 · Concepts and mathematical foundations

TLS 1.3 outer record header has 5 bytes; encrypted content contains plaintext, inner content type and optional padding, plus AEAD tag (16 bytes in this example). Outer content type is application_data for encrypted records.

Learning objectives

Trace the named operation, reproduce intermediate values, verify the result and explain the consequences of a controlled change.

Prerequisites

Mathematical verification and controlled comparison

Substitute the output into its defining equation or check the protocol invariant. A controlled comparison changes one input while holding others fixed. Cite actual trace values and identify the limitations of the evidence.

Before starting

Environment: standard computer, browser and Python/WSL.

Simulation: Recorded, verified Python scenarios; use Python for arbitrary inputs

Technical scope: Length model only; no ciphertext generated.

TLS records and AEAD

1 · Principles and purpose

The record layer frames data and protects it with negotiated keys. AEAD combines encryption and authentication and binds associated header/context data.

2 · Mathematical and algorithmic foundations

Record header is five bytes in conventional TLS framing. TLS 1.3 inner plaintext includes a content-type byte and optional padding; tag length is suite-specific. Nonces are derived from sequence and static IV, not necessarily sent explicitly.

3 · Worked teaching example

For 20 content bytes, one inner type byte, no padding and a 16-byte tag, TLS 1.3 record total=5+20+1+16=42 bytes. TLS 1.2 overhead depends on selected suite; distinguish record size from IP/TCP overhead.

Verified default trace · 5 intermediate states

Given parameters (teaching example):

{
  "payload": 40,
  "padding": 0
}
StageComputed values
1{ "field": "header", "hex": "1703030039", "bytes": 5 }
2{ "field": "application data", "bytes": 40 }
3{ "field": "inner type", "bytes": 1 }
4{ "field": "zero padding", "bytes": 0 }
5{ "field": "AEAD tag", "bytes": 16 }

Recorded result

{
  "wire_bytes": 62,
  "record_length": 57,
  "overhead": 22
}

Captured earlier local execution. Randomized values and timing can differ; compare the invariant.

4 · Verification and experimental interpretation

Step through the following visualization and compare the named operation with the corresponding computed state. Check the mathematical invariant, inverse operation or protocol acceptance condition. Change one input at a time; distinguish a measured output from a prediction.

TLS 1.3 record boundary and AEAD

TLSInnerPlaintext = content || inner content type || zero padding. The five-byte outer header uses application_data (23), legacy version 0x0303 and ciphertext length. For a 16-byte tag, record length = content + 1 + padding + 16. Model uses no compression and checks the TLSCiphertext length bound of 2^14 + 256 bytes; the encrypted inner plaintext must also respect the applicable inner-size limit. The record AEAD exercise is an isolated record-shaped example, not a TLS connection.

Use the operation-by-operation diagram below. The highlighted stage follows the active Simulation trace. Change inputs in Simulation, then return here to inspect the updated sequence.

Mathematical representation and interpretation

TLS 1.3 record sizing

Five bytes are the outer header, one byte is the inner content type. The padding and content must obey the TLS 1.3 record bounds; the authentication tag length depends on the AEAD suite.

\[L_{\mathrm{wire}}=5+L_{\mathrm{content}}+1+L_{\mathrm{padding}}+L_{\mathrm{tag}}\]

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.

TLS record framing and AEAD overhead: independent state notebook12345Calculated state 1fieldheaderhex1703030039bytes5

Step 1 of 5 · Calculated state 1

Calculated state 1

field
header
hex
1703030039
bytes
5

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

Shared research workbenches · network designer & advanced studies
Concurrent-device simulation & Monte Carlo research
Distributed digital twin · topology, protocol & battery research

03 · Interactive simulation

Baseline diagram loaded. Interactive engine initializing…

Calculated baseline diagram · enable JavaScript to explore changed inputs.
TLS 1.3 · record framingTLS 1.3 · record framing54016header · 5 Bapplication data · 40 Binner type · 1 Bzero padding · 0 BAEAD tag · 16 BHeader 1703030039 · wire 62 B · overhead 22 B

Edit the parameters, then Calculate / run. The local model recomputes the trace. No remote service or host configuration is changed.

Calculated result · current inputs

{
  "wire_bytes": 62,
  "record_length": 57,
  "overhead": 22
}
Complete trace

Dr. Mohammad · contextual guide

Guided simulation activity

For payloads 0, 40 and 128 bytes, choose padding 0 then 16. Record header hexadecimal, outer length and wire length. Verify wire_bytes = 5 + payload + 1 + padding + 16. In Python run record_aead.py and explain why altered associated data, ciphertext and tag fail verification.

Continue to practical experiments →

04 · Experiments and engineering investigations

Analytical preparation — before Python

TLS 1.3 outer record header has 5 bytes; encrypted content contains plaintext, inner content type and optional padding, plus AEAD tag (16 bytes in this example). Outer content type is application_data for encrypted records.

Predict the baseline result before revealing the calculated state. A controlled comparison changes the named input while keeping the other conditions fixed. Record an observed value separately from an expected value.

Part A · Independent theoretical exercises

Complete each question before running the simulator or Python. Show calculations or protocol traces. The teaching example is a method, not a substitute for the assigned values.

01 · Application and derivation

Application and derivation · Independent work

For a synthetic TLS record, identify header, plaintext, authenticated-encryption tag and any modeled overhead. Calculate the total using the displayed field lengths and explain why the nonce is not necessarily transmitted as a separate field.

02 · Record calculation

Record calculation · Independent work

A TLS1.3 AES-GCM record carries 60 application bytes, 3 padding bytes, 1 inner type byte and 16 tag bytes. Calculate encoded ciphertext length, total wire length and overhead with 5-byte outer header.

Required evidence: state the expected invariant or acceptance condition; record hand-derived results, compare with the simulator or Python trace, and explain the first discrepancy. Do not report a predicted value as a measurement.

Expanded independent theoretical exercise bank

Progress from calculation and interpretation to diagnosis and controlled engineering design. Complete the questions without opening the simulation first; show intermediate steps.

Intermediate · Alternate configuration

Independent theoretical exercise · CR79-01

For the separate teaching-test configuration payload: 40; padding: 16, predict wire_bytes using the relevant operation or decision rule. Show intermediate work and state whether this is a deterministic result.

Intermediate · Interpret a computation state

Independent theoretical exercise · CR79-02

A teaching trace for TLS record framing and AEAD overhead contains field: application data; bytes: 40. Explain the role of bytes (recorded value 40) and identify the rule or input that determines it. Distinguish an intermediate state from the final result.

Intermediate · Compare two recorded states

Independent theoretical exercise · CR79-03

The first and final trace records show bytes = 5 and 16. Calculate the signed difference and explain whether it is an operation count, a state value or a measurement.

Challenging · Controlled algorithm verification

Independent theoretical exercise · CR79-04

Plan a comparison of payload: 40; padding: 0 with payload: 40; padding: 16. Record the dependent value wire_bytes, identify the changed factor(s), and describe the verification and failure criterion without claiming a real security measurement.

Part B · Guided simulation and practical procedure

Before starting — tools and setup

Standard computer; extract the WSL toolkit into a new directory. For the browser activity, use the integrated workstation. Verified browser scenarios; arbitrary inputs in Python (protocol simulations are models unless identified as executed local protocol tests).

Install Python dependencies only if required by the selected toolkit README. Use its requirements file and virtual environment instructions.

Open complete, verified WSL commands in Part C ↓

01

Baseline calculation or protocol trace

  1. Use the exact baseline input below and write a prediction.
  2. Select the baseline configuration below. Predict the relevant operation using the theory; execute the workstation and record the first and final state. Reproduce the same input with Python.
  3. Save the trace and compare it with the reference output.

Experimental inputs

Experimental reference · json
{"payload":40,"padding":0}
Verified baseline reference (check after predicting)
Experimental reference · json
{"wire_bytes":62,"record_length":57,"overhead":22}

Compare your baseline with the verified reference output below; for runtime-dependent results, compare invariants and report actual measurements instead of expecting identical timing or randomly generated values.

Evidence to record

Record the named intermediate values and final outputs from the selected trace.

Run baseline →
02

Part D · Controlled investigation

  1. For payloads 0, 40 and 128 bytes, choose padding 0 then 16. Record header hexadecimal, outer length and wire length. Verify wire_bytes = 5 + payload + 1 + padding + 16. In Python run record_aead.py and explain why altered associated data, ciphertext and tag fail verification.
  2. Record inputs and complete traces for each trial, holding all other parameters constant.
  3. Compare Python results to the corresponding browser model; report any difference in scope or measured behavior.
TrialInput configurationPredictionObservedVerification
1{"payload":40,"padding":0}
2{"payload":40,"padding":16}

Use the table as a recording template; enter your own measured values in the field below or reproduce it in your report.

Return to simulation →

Observation table

Trial inputsLast completed step / fieldResult and verificationInterpretation
RecordRecordRecordExplain
RecordRecordRecordExplain
RecordRecordRecordExplain
RecordRecordRecordExplain
03

Part E/F · Independent Python verification and deliverables

  1. Download the notebook or toolkit and run the default example.
  2. Reproduce at least one changed input; compare the intermediate values with the browser where supported.
  3. Complete the independent assessment below without copying the worked baseline. Explain discrepancies and distinguish mathematical results from security claims.
Additional investigation instructions
  1. Read the theory and prerequisite labs. Run the baseline and record the input and result.
  2. Change padding from 0 to 16; record outer length and overhead. Explain why the header length differs from application length.
  3. Locate the first intermediate step where the two cases differ. Verify the defining equation or decision rule.
  4. Submit a two-row comparison table, trace evidence and a conclusion with limitations.
CaseInputObserved resultVerificationLimitation
BaselineRecordRecordDeriveExplain
ChangedRecordRecordDeriveExplain

Part C · Python, Google Colab and WSL

WSL / Linux execution workflow

Use Ubuntu or Kali WSL, not PowerShell. Download the toolkit above to your computer. If Python, venv or unzip is missing, install these prerequisites once (requires administrator permission and network access).

Optional prerequisites · bash
sudo apt update
sudo apt install -y python3 python3-venv unzip

In WSL, enter the actual downloaded ZIP path when prompted (for example, a file under /mnt/c/Users/…/Downloads). Extract to a new, dedicated directory. If this directory already exists from a previous extraction, use the existing verified toolkit or choose a clean directory rather than overwriting it.

Step 1 · Extract · bash
read -r -p "Full path to PSUT_V22_9_9_Cryptography_WSL.zip: " ZIP
DEST="$HOME/psut-crypto-v22.9.9"
if [ -f "$ZIP" ] && [ ! -e "$DEST" ]; then
    mkdir "$DEST" && unzip "$ZIP" -d "$DEST"
else
    echo "Check ZIP path and use a fresh destination."
fi

Create the isolated environment in the extracted toolkit root, activate it, then enter this experiment’s actual folder. Install only its declared dependencies. A comment-only requirements file requires no third-party packages.

Step 2 · Activate and install · bash
cd ~/psut-crypto-v22.9.9
python3 -m venv .venv
source .venv/bin/activate
cd CR79
ls
python -m pip install -r requirements.txt

Execute the default run and save the genuine program output. Then run the supplied regression test and the baseline fixture through the explicit input interface.

Step 3 · Run and verify · bash
python lab.py | tee my-results.json
python test_lab.py
python lab.py --inputs "$(cat example-input.json)"
python -m json.tool my-results.json

To change inputs, copy example-input.json, edit the copy in a text editor and run the command below. The original fixture is preserved.

Step 4 · Change an input · bash
cp example-input.json my-input.json
# Edit my-input.json with your preferred editor.
python lab.py --inputs "$(cat my-input.json)"

These scripts terminate normally. Use Ctrl+C to stop a long-running calculation if needed. When finished, leave the isolated virtual environment; no global service cleanup is required for these local examples.

Step 5 · Finish · bash
deactivate

Declared dependencies: # Python standard library only

Expected terminal output — captured local execution

This excerpt contains the actual first trace step and final result from python lab.py, followed by the actual regression test output. Full stdout is in CR79/verified-output.txt inside the toolkit. Timing, random signatures, keys, certificate fields and implementation-dependent sizes can vary; compare the invariant and record your own observations.

Verified execution excerpt · text
{
  "first_step": {
    "field": "header",
    "hex": "1703030039",
    "bytes": 5
  },
  "result": {
    "wire_bytes": 62,
    "record_length": 57,
    "overhead": 22
  }
}

Test script output:
CR79 PASS

Check the output JSON and the test exit status. An assertion error means the expected invariant was not met. If Python reports a missing module, activate the environment and install the experiment’s requirements file; if a file is missing, check pwd and ls.

Download the notebook, open Google Colab and upload it using File → Upload notebook. For local Linux/WSL execution, follow the command blocks below in order.

Inspect Python source
Documented Python implementation · python
# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR79
# Experiment: tls record framing and aead overhead
# Purpose: expose algorithm states and verify the experiment invariant.
# ------------------------------------------------------------
# CR79 | TLS record framing and AEAD overhead
# Execute the named operation; expose states and assert the laboratory invariant.
import json



DEFAULT={'payload': 40, 'padding': 0}
ALTERNATE={'padding': 16}

def run(overrides=None):
    # Merge only explicitly supplied inputs with the lecture baseline.
    params={**DEFAULT, **(overrides or {})}
    payload=params['payload']
    padding=params['padding']
    if type(payload) is not int or type(padding) is not int or payload<0 or payload>16384 or padding<0 or payload+padding>16384 or payload+1+padding+16>16640:raise ValueError('record size out of model range')
    inner=payload+1+padding;length=inner+16;header=bytes([23,3,3])+length.to_bytes(2,'big');steps=[{'field':'header','hex':header.hex(),'bytes':5},{'field':'application data','bytes':payload},{'field':'inner type','bytes':1},{'field':'zero padding','bytes':padding},{'field':'AEAD tag','bytes':16}];result={'wire_bytes':length+5,'record_length':length,'overhead':length+5-payload}
    # Independently check the stated mathematical or protocol invariant.
    assert result["wire_bytes"]==sum(s["bytes"] for s in steps), "verification failed"
    return {"steps":steps,"result":result}

if __name__ == "__main__":
    import argparse
    parser=argparse.ArgumentParser();parser.add_argument("--inputs",default="{}");parser.add_argument("--test",action="store_true");args=parser.parse_args()
    if args.test:
        for case in [{},ALTERNATE]:run(case)
        print("PASS")
    else:print(json.dumps(run(json.loads(args.inputs)),indent=2))
Baseline reference (randomized fields may vary)
Reference result · json
{
  "wire_bytes": 62,
  "record_length": 57,
  "overhead": 22
}

Additional practical · authenticated record-shaped data

Run the local AES-GCM example after installing the declared dependencies. This demonstrates authentication of the outer header and rejection of tampered data; it does not establish a TLS connection.

Run the local AEAD practical · bash
python record_aead.py
Captured local output · text
{
  "header": "1703030049",
  "wire_bytes": 78,
  "recovered": true,
  "header_change_rejected": true,
  "ciphertext_change_rejected": true,
  "tag_change_rejected": true
}
Teaching implementation · python
# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR79
# Local record-shaped AES-GCM verification, not a TLS session.
# Uses a fresh key and IV per run. No traffic is sent.
# ------------------------------------------------------------
import json
from secrets import token_bytes
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.exceptions import InvalidTag

def record_trial(payload=40, padding=16):
    """Bind a TLS-shaped outer header as associated data; test tampering."""
    if type(payload) is not int or type(padding) is not int or min(payload,padding)<0 or payload+padding>16384:
        raise ValueError('Inner plaintext exceeds the classroom limit')
    inner=b'A'*payload+b'\x17'+bytes(padding)
    header=b'\x17\x03\x03'+(len(inner)+16).to_bytes(2,'big')
    aes=AESGCM(AESGCM.generate_key(bit_length=128))
    iv=token_bytes(12) # Single record; never reuse this key/nonce pair.
    ciphertext=aes.encrypt(iv,inner,header)
    ok=aes.decrypt(iv,ciphertext,header)==inner
    def rejected(body, associated):
        try: aes.decrypt(iv,body,associated)
        except InvalidTag: return True
        return False
    return {'header':header.hex(),'wire_bytes':5+len(ciphertext),'recovered':ok,
            'header_change_rejected':rejected(ciphertext,bytes([header[0]^1])+header[1:]),
            'ciphertext_change_rejected':rejected(bytes([ciphertext[0]^1])+ciphertext[1:],header),
            'tag_change_rejected':rejected(ciphertext[:-1]+bytes([ciphertext[-1]^1]),header)}
if __name__=='__main__':
    result=record_trial(); print(json.dumps(result,indent=2)); assert all(result[k] for k in ['recovered','header_change_rejected','ciphertext_change_rejected','tag_change_rejected'])

05 · Interactive flashcards

Recall before revealing. Review and mastery ratings remain on this device.

Browse all explanations
What is the defining principle?

TLS 1.3 outer record header has 5 bytes; encrypted content contains plaintext, inner content type and optional padding, plus AEAD tag (16 bytes in this example). Outer content type is application_data for encrypted records.

How do I verify the result?

Change padding from 0 to 16; record outer length and overhead. Explain why the header length differs from application length.

What does this experiment not establish?

Length model only; no ciphertext generated.

What input settings define the baseline for this experiment?

payload = 40; padding = 0

What is the first intermediate state in the baseline?

field: header; hex: 1703030039; bytes: 5

06 · Knowledge assessment

Change padding from 0 to 16; record outer length and overhead. Explain why the header length differs from application length. Choose one valid input not included in the browser cases, calculate it in Python, and explain the first changed intermediate value. Include a failure or boundary case where applicable. Criteria: mathematical correctness 40%, reproducible evidence 30%, interpretation 20%, scope 10%.

Part F · Engineering evidence record

Record the baseline, prediction, changed input, observed result, discrepancy and limitation. Save locally or export with the displayed result. This is not an official submission.

All Cryptography Engineering labsNext laboratory · CR80 →