Compare block modes, verify decryption and file layout, derive keys from passwords, and recover an encrypted training image.
The focus of this experiment is to compare ECB and CBC, padding and password-based key derivation. Students then trace block recovery and encrypted-file handling, and verify correct and incorrect password or integrity conditions without treating CBC alone as AEAD. The Concepts view explains the operation before the practical work; the Simulation view is used to examine reference and changed inputs, not to substitute for actual measurements.
Learning objectives
Compare ECB and CBC, padding and password-based key derivation.
Trace block recovery and encrypted-file handling.
Verify correct and incorrect password or integrity conditions without treating CBC alone as AEAD.
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 compare ECB and CBC, padding and password-based key derivation, trace block recovery and encrypted-file handling, and verify correct and incorrect password or integrity conditions without treating CBC alone as AEAD.
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 correct and incorrect password or integrity conditions without treating CBC alone as AEAD. Separate predicted values from observations.
Prerequisite knowledge and related learning
Review the foundational terminology in Concepts and confirm readiness using the existing setup instructions. After completion, continue to K01 · Environment & scope.
Environment and experimental methodology
The included teaching workstation and the listed Python/Colab or WSL implementation. Historical and small-number constructions are instructional, not deployment recommendations.
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.
How to investigate AES modes — ECB, CBC, padding, password derivation and encrypted files
Compare block modes, verify decryption and file layout, derive keys from passwords, and recover an encrypted training image.
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: Compare block modes, verify decryption and file layout, derive keys from passwords, and recover an encrypted training image.
Complete the analytical preparation below before programming. Show the intermediate mathematical calculations.
ECB versus CBC — complete its numbered steps and record the requested evidence.
Padding and classroom binary exchange — complete its numbered steps and record the requested evidence.
Password derivation and file recovery — complete its numbered steps and record the requested evidence.
Reference check: ECB yields identical ciphertext for identical aligned blocks; CBC with distinct chaining values differs. Correct KDF/IV and unpadding recover exactly the original bytes.
Model boundary: Fictional educational inputs. Browser algorithms and reference programs; no hardware or live-network measurements. Supplied starter notebooks may be incomplete; trace playback is recorded execution, not arbitrary Python running in browser.
Independent task and submission evidence
2. ECB versus CBC — complete its numbered steps and record the requested evidence. 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.
Trial
Changed setting
Fixed settings
Predicted result
Actual observation / units
Evidence / uncertainty
A: baseline
Reference
Record
Predict
Record
Record
B: one change
Record
Same as A
Predict
Record
Record
A: repeat
Restore
Same as A
Predict
Record
Record
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.
Scientific concept map: Plaintext — Block padding; ECB — Independent blocks; CBC — XOR previous ciphertext; PBKDF2 — Salt + iterations; File envelope — IV and ciphertext.
Block modes
AES operates on 16-byte blocks. ECB encrypts each block independently and leaks equality of repeated blocks. CBC XORs each plaintext block with the preceding ciphertext, starting with an unpredictable IV; it needs padding for unaligned data and separate integrity protection.
Padding and binary representation
PKCS#7 appends bytes whose value equals the padding length, including a full block when the message is already aligned. Base64 transports bytes as text without adding confidentiality. Decrypt using the matching key, IV and mode, then remove padding and check the entire plaintext.
Password-derived keys and files
PBKDF2 derives key material from a password, random salt, PRF and iteration count. Save the salt and IV in a documented envelope so the receiver can reconstruct the key and decrypt. The lab fixture uses a fixed documented configuration for reproducibility; deployed systems need authenticated encryption and appropriately tuned KDF parameters.
Prerequisites: EC11 and earlier foundations as applicable.
Algorithm structure and data flow. Use the simulation to inspect the corresponding numerical transformations.
Engineering diagrams
CBC chaining and IV dependency.
Scientific foundations and worked examples
Mode equations and repeated blocks
ECB uses \(C_{i}\)=\(E_{k}\)(\(P_{i}\)); equal plaintext blocks produce equal ciphertext blocks. CBC uses \(C_{i}\)=\(E_{k}\)(\(P_{i}\) XOR \(C_{i-1}\)), with \(C_{0}\)=IV. Decrypt by \(P_{i}\)=\(D_{k}\)(\(C_{i}\)) XOR \(C_{i-1}\). CBC needs an unpredictable fresh IV; its secrecy is not required. ECB and CBC require complete blocks; PKCS#7 appends n copies of the byte n, including a whole extra block for already aligned data. Neither mode inherently authenticates ciphertext.
Binary serialization, passwords and file formats
Base64 represents bytes as printable text; it provides no secrecy. PBKDF2 derives a key from password, salt, iteration count, PRF and output length. Random salt prevents reuse of precomputed guesses, not weak passwords. To reproduce a file key, record every KDF parameter. For an IV||salt||ciphertext format with 16-byte IV and salt, bytes 0–15 and 16–31 are header fields and the remaining bytes are ciphertext. Recover using the exact agreed KDF and padding; do not guess omitted parameters. Modern file protection uses authenticated encryption and authenticates format metadata.
Controlled comparison and sharing
Use the same laboratory key and plaintext across mode comparisons; vary the IV alone to isolate its effect. In a peer exchange encode key, IV and ciphertext separately for the classroom exercise and verify decoding before decrypting. A real system must not send a secret key through the same unprotected channel. Use authenticated key exchange or a properly authenticated public key instead.
Engineering principles · additional worked teaching example
CBC chains each block via XOR with previous ciphertext, using an unpredictable IV. PKCS#7 padding appends n bytes each equal to n; for 16-byte blocks and 13 data bytes, append 03 03 03. CBC alone does not authenticate ciphertext; use a suitable authenticated scheme for real applications.
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.
Worked engineering reasoning and boundary conditions
ECB encrypts blocks independently; CBC chains XOR with previous ciphertext; CTR uses unique nonce/counter streams. PKCS#7 appends padding even for aligned data. AEAD provides integrity with confidentiality.
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 · operation pathway
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.
Step 1 of 4 · Plaintext length
Plaintext length
Plaintext length
31 bytes
Pad
Plaintext length
31 bytes
Pad
one byte 01
CBC chain
Plaintext length
31 bytes
Pad
one byte 01
CBC chain
C1=E(P1 XOR IV)
Validate
Plaintext length
31 bytes
Pad
one byte 01
CBC chain
C1=E(P1 XOR IV)
Validate
decrypt and authenticate before use
Teaching example only; inspect live calculations or real practical evidence separately.
Interactive flashcards
Self-rated study progress is stored locally, not used for official grades.
Browse all explanationsWhat leaks in ECB?
Equal plaintext blocks produce equal ciphertext blocks under one key.
Why randomize CBC IV?
To prevent deterministic first-block encryption.
What does PBKDF2 do?
Derives a key from a password with salt and iteration cost.
Does CBC padding authenticate data?
No; use authenticated encryption or proper authentication.
Why does ECB reveal repeated plaintext blocks?
Identical blocks under the same key yield identical ciphertext blocks.
What does CBC XOR before block encryption?
The preceding ciphertext block, or IV for the first block.
What is PKCS#7 padding for a full AES block?
An additional 16-byte block with each byte 0x10.
Why use a random CBC IV?
To avoid predictable first-block encryption patterns.
Is Base64 encryption?
No, it is reversible encoding.
What does a PBKDF2 salt accomplish?
It prevents reuse of precomputed password-derived keys across different salts.
What parameters must match to reproduce PBKDF2?
Password encoding, salt, PRF, iteration count and derived key length.
Does CBC alone authenticate a file?
No.
Why distinguish the replacement image fixture from the model?
The original KDF parameters were incomplete.
What should be checked after file decryption?
Padding, expected file format and authenticated integrity where available.
Why do identical plaintext blocks under ECB often reveal structure?
The same key encrypts identical blocks to identical ciphertext blocks.
If the final plaintext exactly fills the AES block, how many PKCS#7 padding bytes are appended?
A full 16-byte padding block; each byte has value 0x10.
Which parameters are required to reproduce a password-derived encryption key?
Password encoding, KDF, salt, iteration/work factor, PRF, output length and any other KDF-specific settings.
Choose a workstation, edit the inputs, and observe recalculated results. Play or step through the actual calculation trace. Hash-search stations calculate successive candidates during playback. All inputs are fictional training data.
Where the browser requires Web Crypto, launch the local portal on localhost or use the HTTPS deployment. The classroom algorithms and keys are not intended for production use.
Independent theoretical exercises
Complete every question independently on paper or in the fields below before using the simulation or programming activities. Show formulas, intermediate steps, tables, proofs and units. Afterward verify your work using the simulator and Python, and explain discrepancies. Worked examples in Concepts do not replace your own derivation.
01 · ECB and CBC
Draw block equations for b'Encrypt 16 Bytes' and its repeated two-block form using the assigned classroom key. Predict equality patterns under ECB and CBC and the effect of changing only the IV.
Engineering method — CBC chains each block via XOR with previous ciphertext, using an unpredictable IV. PKCS#7 padding appends n bytes each equal to n; for 16-byte blocks and 13 data bytes, append 03 03 03. CBC alone does not authenticate ciphertext; use a suitable authenticated scheme for real applications. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
02 · Padding
Calculate PKCS#7 padding bytes for the 16-byte message and b'AES is the Advanced Encryption Standard'. Explain the aligned-block case.
Engineering method — CBC chains each block via XOR with previous ciphertext, using an unpredictable IV. PKCS#7 padding appends n bytes each equal to n; for 16-byte blocks and 13 data bytes, append 03 03 03. CBC alone does not authenticate ciphertext; use a suitable authenticated scheme for real applications. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
03 · Binary format
Calculate offsets for the 16-byte IV, 16-byte salt and remaining ciphertext. Explain Base64, KDF parameters and why a salt must be retained. Predict what happens if the wrong parameters are used.
Engineering method — CBC chains each block via XOR with previous ciphertext, using an unpredictable IV. PKCS#7 padding appends n bytes each equal to n; for 16-byte blocks and 13 data bytes, append 03 03 03. CBC alone does not authenticate ciphertext; use a suitable authenticated scheme for real applications. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
04 · Peer and file exercises
Design the encryption/decryption steps and evidence for the existing peer exchange and encrypted-file tasks. Distinguish the incomplete original challenge parameters from the reproducible replacement.
Engineering method — CBC chains each block via XOR with previous ciphertext, using an unpredictable IV. PKCS#7 padding appends n bytes each equal to n; for 16-byte blocks and 13 data bytes, append 03 03 03. CBC alone does not authenticate ciphertext; use a suitable authenticated scheme for real applications. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
05 · Calculation
Calculation · Independent work
For 32 bytes of plaintext with AES block size16, derive PKCS#7 padding length and padded length. Why not omit padding in the aligned case?
Calculation — CBC chains each block via XOR with previous ciphertext, using an unpredictable IV. PKCS#7 padding appends n bytes each equal to n; for 16-byte blocks and 13 data bytes, append 03 03 03. CBC alone does not authenticate ciphertext; use a suitable authenticated scheme for real applications. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
Responses are saved locally when browser storage is available. Export your work for submission. No automatic grading or remote upload occurs.
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.
Foundational · Apply the principle
Independent theoretical exercise · EC12-01
For 16-byte block size and a 31-byte message, state padding.
Intermediate · Calculate or trace
Independent theoretical exercise · EC12-02
For exactly 32 bytes, give PKCS#7 padding length and byte value.
Intermediate · Interpret the result
Independent theoretical exercise · EC12-03
Two identical plaintext blocks under ECB same key: compare ciphertext.
Advanced · Analyze a condition
Independent theoretical exercise · EC12-04
For CBC with IV I, express C1 and C2.
Advanced · Diagnose or compare
Independent theoretical exercise · EC12-05
A CTR ciphertext bit changes; predict decrypted bit effect.
Challenging · Engineering verification
Independent theoretical exercise · EC12-06
Propose authenticated file storage with password.
Activity sequence
Follow the setup commands, then each named activity. The detailed instructions, given values and recording fields appear below.
Complete the analytical preparation below before programming. Show the intermediate mathematical calculations.
ECB versus CBC — complete its numbered steps and record the requested evidence.
Compare observations with the reference checks and submit the required evidence.
Analytical preparation — before Python
Complete this written or hand-calculation activity first, then compare it with the simulator and executable implementation.
Write ECB and CBC equations and sketch two equal input blocks. Calculate padding for aligned and unaligned input and identify the exact byte offsets of IV and salt.
Evidence: show the derivation, intermediate values and independent checks; explain any mismatch with the practical result.
Practical laboratory manual
Scientific experimental protocol
Research question: How do mode, IV and padding affect ciphertext structure and file recovery?
Independent variables
Mode, message, IV, salt, password, iteration count
Keep key and plaintext fixed for ECB/CBC comparison; use a fresh IV in real CBC encryption.
Validation and evidence
Before running a trial, predict its output. Use the baseline conditions below to check your method, then vary one independent variable. Save calculated outputs or the actual Python trace. Keep browser results and local Python execution distinct.
Trial
Controlled configuration
Reference check
Student observation (editable)
ECB
Two identical 16-byte blocks
Identical ciphertext blocks
Enter observation
CBC
Same input, IV provided
Round trip recovers exact bytes; identical blocks generally differ
Enter observation
Training envelope
Verified portal fixture; correct demo password
Recovered bitmap matches known local fixture
Enter observation
Analysis: Document the envelope format and key-derivation parameters. Treat the model file separately because those parameters are incomplete. CBC is not authenticated.
Compare block modes, verify decryption and file layout, derive keys from passwords, and recover an encrypted training image.
Equipment and execution
Browser-based simulator, Python 3, notebook or local evidence folder. Use WSL Setup only if you need a Linux runtime.
3. Run the check before changing inputs. Record the exact Python version and any dependency error. Use Python visualizer to inspect the recorded traces; for edited code, generate and import a new trace using the instructions in that tab.
Complete the activities in order. Hold the controlled conditions fixed, record the input and actual output, and compare your observations with an independent calculation or test vector.
01
ECB versus CBC
Open the exact workstation
Choose the relevant tab below, enter the assigned values in the activity steps, then use Step or Play to inspect intermediate calculations. Return to Experiment and record the results before changing the input.
Use exact b"Encrypt 16 Bytes" and b"TESTKEY testkey.". Encrypt/decrypt one aligned block in ECB, then the repeated two-block string.
Repeat CBC twice with fresh IVs and compare outputs; encrypt the repeated two-block message and inspect block chaining.
Store the encryption object .iv, supply it to decryption and verify exact plaintext. Compare equal plaintext blocks under ECB and CBC.
Evidence to record
Ciphertext blocks, IVs and recovered bytes.
Verification: Record the baseline and modified input separately, note the observed intermediate values, compare with the assigned calculation, and explain any mismatch. Do not replace observations with expected values.
02
Padding and classroom binary exchange
Open the exact workstation
Choose the relevant tab below, enter the assigned values in the activity steps, then use Step or Play to inspect intermediate calculations. Return to Experiment and record the results before changing the input.
Attempt b"AES is the Advanced Encryption Standard" without padding; record alignment error. Apply PKCS#7 pad/unpad and verify recovery.
Generate a random 128-bit demo key, encrypt fictional data in CBC, Base64-encode key, IV and ciphertext, and decode in a local classroom exchange. Do not transmit real keys by ordinary email.
Optionally repeat with OFB, CFB or CTR using their appropriate IV/nonce handling.
Evidence to record
Alignment error, padded size, round-trip and encoded demo fields.
Verification: Record the baseline and modified input separately, note the observed intermediate values, compare with the assigned calculation, and explain any mismatch. Do not replace observations with expected values.
03
Password derivation and file recovery
Open the exact workstation
Choose the relevant tab below, enter the assigned values in the activity steps, then use Step or Play to inspect intermediate calculations. Return to Experiment and record the results before changing the input.
Generate 16-byte salt using get_random_bytes; derive 16-byte key using PBKDF2 and document PRF and iterations. Read/write binary files.
Encrypt/decrypt a small local file; use the envelope IV[0:16] || salt[16:32] || ciphertext[32:] for CBC.
Investigate the binary envelope and KDF settings specified in the reproducible fixture. Record the KDF algorithm and iteration count before attempting recovery.
Run the verified replacement fixture using the explicit settings already included in the practical toolkit; compare recovered bytes and record the result separately.
For the reproducible encrypted file, use PBKDF2-HMAC-SHA256, 10,000 iterations and a 16-byte key. This iteration count is a fixed classroom fixture, not a production recommendation. From the extracted toolkit root run
Compare the recovered byte count and inspect the file header.
Optional incomplete-data investigation: download the additional encrypted file. Its PRF and iteration count are unspecified. State why the available bytes alone are insufficient to reproduce the KDF. Do not report an image recovery unless independently verified.
Verification: Record the baseline and modified input separately, note the observed intermediate values, compare with the assigned calculation, and explain any mismatch. Do not replace observations with expected values.
Challenge data and additional questions
Portal training fixture: assets/essential/challenges/encrypted-image.bin. Demo password: portal-lab12. Format: 16-byte IV || 16-byte salt || AES-128-CBC ciphertext; PBKDF2-HMAC-SHA256 with 10,000 iterations, 16-byte derived key; PKCS#7. This is a replacement practice file with fully specified parameters.
Run this command from the toolkit’s code directory. Do not use a real password in this exercise.
Verification criteria
ECB yields identical ciphertext for identical aligned blocks; CBC with distinct chaining values differs. Correct KDF/IV and unpadding recover exactly the bytes.
Deliverables
Submit ECB/CBC comparisons, alignment-error evidence, Base64 round trip, KDF settings and recovered training image. Never include real passwords or keys.
Download this notebook and open Google Colab. Select File → Upload notebook and choose the downloaded .ipynb.
Read the Markdown instructions before each executable cell. Use a Python runtime, run cells from top to bottom, and resolve imports if necessary.
Perform the baseline and controlled changes. Save the notebook with actual outputs and your written interpretation.
Execution scope: Fictional educational inputs. Browser algorithms and reference programs; no hardware or live-network measurements. Supplied starter notebooks may be incomplete; trace playback is recorded execution, not arbitrary Python running in browser. Default computational cells passed isolated local Python execution; physical equipment and live services require separate verification.
01Instructions · Markdown
# EC12 · AES modes — ECB, CBC, padding, password derivation and encrypted files
**PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh**
## 1. Scientific objective
Follow the setup commands, then each named activity. The detailed instructions, given values and recording fields appear below.
Complete the analytical worksheet in the portal first. Record your predictions before running this notebook. This notebook is a bounded local computational investigation; use the portal’s separate WSL, hardware or Remix procedure for real interfaces.
02Instructions · Markdown
## Experiment-specific preparation
Compare block modes, verify decryption and file layout, derive keys from passwords, and recover an encrypted training image.
**Reference procedure (use the matching simulator/WSL tool where named, not an unrelated service):**
1. Complete the analytical preparation below before programming. Show the intermediate mathematical calculations.
2. ECB versus CBC — complete its numbered steps and record the requested evidence.
3. Padding and classroom binary exchange — complete its numbered steps and record the requested evidence.
4. Password derivation and file recovery — complete its numbered steps and record the requested evidence.
5. Compare observations with the reference checks and submit the required evidence.
**Evidence:** ECB yields identical ciphertext for identical aligned blocks; CBC with distinct chaining values differs. Correct KDF/IV and unpadding recover exactly the original bytes.
**Boundary:** Fictional educational inputs. Browser algorithms and reference programs; no hardware or live-network measurements. Supplied starter notebooks may be incomplete; trace playback is recorded execution, not arbitrary Python running in browser.
03Instructions · Markdown
## 2. Reference configuration and investigation
1. Complete the analytical preparation below before programming. Show the intermediate mathematical calculations.
2. ECB versus CBC — complete its numbered steps and record the requested evidence.
3. Padding and classroom binary exchange — complete its numbered steps and record the requested evidence.
4. Password derivation and file recovery — complete its numbered steps and record the requested evidence.
5. Compare observations with the reference checks and submit the required evidence.
Run cells in order; do not substitute model results for physical measurements.
04Instructions · Markdown
### Environment
Colab usually provides cryptography. If imports fail, install dependencies in a separate Colab cell using `%pip install pycryptodome cryptography`, then restart the runtime. Local validation uses the installed backend. No actual secrets are used.
05Instructions · Markdown
### Dependency — crypto_backend
The following cells define the actual toolkit dependency.
06Instructions · Markdown
Dependency definitions 1
07Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC12 | Code cell 01 | AES modes — ECB, CBC, padding, password derivation and encrypted files
# Purpose: Dependency definitions 1
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
"""Reference library adapter for classroom AES. No production key storage."""
try:
from Crypto.Cipher import AES as _AES
BACKEND='PyCryptodome'
except ImportError:
from cryptography.hazmat.primitives.ciphers import Cipher,algorithms,modes
_AES=None; BACKEND='cryptography'
# Define the reusable operation aes crypt; keep its logic separate from the trial.
def aes_crypt(key,data,mode,iv=b'',decrypt=False):
if len(key) not in (16,24,32): raise ValueError('Invalid AES key length')
if mode in ('ECB','CBC') and len(data)%16: raise ValueError('Unaligned block-mode data')
if mode=='CBC' and len(iv)!=16: raise ValueError('CBC requires 16-byte IV')
if mode=='CTR' and len(iv)!=8: raise ValueError('This CTR fixture uses an 8-byte nonce')
if mode not in ('ECB','CBC','CTR'): raise ValueError('Unknown mode')
if _AES is not None:
if mode=='ECB': c=_AES.new(key,_AES.MODE_ECB)
elif mode=='CBC': c=_AES.new(key,_AES.MODE_CBC,iv=iv)
else: c=_AES.new(key,_AES.MODE_CTR,nonce=iv,initial_value=0)
return c.decrypt(data) if decrypt else c.encrypt(data)
m={'ECB':lambda:modes.ECB(),'CBC':lambda:modes.CBC(iv),'CTR':lambda:modes.CTR(iv+b'\0'*8)}[mode]()
c=Cipher(algorithms.AES(key),m); op=c.decryptor() if decrypt else c.encryptor()
return op.update(data)+op.finalize()
# =====================================================================
# EC12 | Code cell 02 | AES modes — ECB, CBC, padding, password derivation and encrypted files
# Purpose: Dependency definitions 2
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Define the reusable operation pad; keep its logic separate from the trial.
def pad(data):
n=16-len(data)%16; return data+bytes([n])*n
# Define the reusable operation unpad; keep its logic separate from the trial.
def unpad(data):
if not data or len(data)%16: raise ValueError('Invalid padded data length')
n=data[-1]
if not 1<=n<=16 or data[-n:]!=bytes([n])*n: raise ValueError('Invalid PKCS#7 padding')
return data[:-n]
# =====================================================================
# EC12 | Code cell 03 | AES modes — ECB, CBC, padding, password derivation and encrypted files
# Purpose: Dependency definitions 2
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
import types, sys
# Set _dependency for the next computation or reference condition.
_dependency = types.ModuleType('crypto_backend')
_dependency.__dict__.update({k:v for k,v in globals().copy().items() if not k.startswith("__")})
# Set sys.modules['crypto_backend'] for the next computation or reference condition.
sys.modules['crypto_backend'] = _dependency
## 3. Algorithm implementation
Read each definition and relate it to the equations and scientific SVGs in Concepts.
12Instructions · Markdown
### Implementation cell 1
Inspect the definitions, then execute to make them available for the investigation.
13Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC12 | Code cell 04 | AES modes — ECB, CBC, padding, password derivation and encrypted files
# Purpose: Implementation cell 1 Inspect the definitions, then execute to make them available for the investigation.
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
"""Essential 12 — AES modes and neutral training-file decryption."""
import base64,hashlib,secrets,argparse
from pathlib import Path
from crypto_backend import aes_crypt,pad,unpad,BACKEND
# Set ITERATIONS for the next computation or reference condition.
ITERATIONS=10000
# Define the reusable operation key from password; keep its logic separate from the trial.
def key_from_password(password,salt):
return hashlib.pbkdf2_hmac('sha256',password.encode(),salt,ITERATIONS,16)
### Implementation cell 2
Inspect the definitions, then execute to make them available for the investigation.
15Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC12 | Code cell 05 | AES modes — ECB, CBC, padding, password derivation and encrypted files
# Purpose: Implementation cell 2 Inspect the definitions, then execute to make them available for the investigation.
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Define the reusable operation encrypt file bytes; keep its logic separate from the trial.
def encrypt_file_bytes(message,password):
iv=secrets.token_bytes(16); salt=secrets.token_bytes(16)
return iv+salt+aes_crypt(key_from_password(password,salt),pad(message),'CBC',iv)
# Define the reusable operation decrypt file bytes; keep its logic separate from the trial.
def decrypt_file_bytes(envelope,password):
if len(envelope)<48 or len(envelope)%16: raise ValueError('Invalid envelope length')
iv,salt,ct=envelope[:16],envelope[16:32],envelope[32:]
return unpad(aes_crypt(key_from_password(password,salt),ct,'CBC',iv,True))
## 4. Execute reference controls
The program checks selected algorithm outcomes. Record the observed output. These checks do not replace the independent calculation assignment.
17Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC12 | Code cell 06 | AES modes — ECB, CBC, padding, password derivation and encrypted files
# Purpose: 4. Execute reference controls The program checks selected algorithm outcomes. Record the observed output. These checks do not replace the independent calculation assignment.
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Set parser for the next computation or reference condition.
parser = argparse.ArgumentParser()
parser.add_argument('--decrypt', type=Path)
parser.add_argument('--output', type=Path)
parser.add_argument('--demo-password', default='portal-lab12')
# Set a for the next computation or reference condition.
a = parser.parse_args([])
if a.decrypt:
if not a.output:
parser.error('--output is required when decrypting a file')
data = decrypt_file_bytes(a.decrypt.read_bytes(), a.demo_password)
a.output.write_bytes(data)
print('Recovered bytes:', len(data))
else:
key = b'TESTKEY testkey.'
b = b'Encrypt 16 Bytes'
iv = secrets.token_bytes(16)
assert len(key) == len(b) == 16
e = aes_crypt(key, b + b, 'ECB')
assert e[:16] == e[16:]
c = aes_crypt(key, b + b, 'CBC', iv)
assert aes_crypt(key, c, 'CBC', iv, True) == b + b
assert base64.b64decode(base64.b64encode(iv)) == iv
message = b'AES is the Advanced Encryption Standard'
assert decrypt_file_bytes(encrypt_file_bytes(message, 'fictional-password'), 'fictional-password') == message
print('ECB/CBC, Base64 and password-based file round-trip passed; backend:', BACKEND)
## 5. Controlled variation
Predict the effect of the parameter changes below. Compare each actual result to your prediction.
19Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC12 | Code cell 07 | AES modes — ECB, CBC, padding, password derivation and encrypted files
# Purpose: 5. Controlled variation Predict the effect of the parameter changes below. Compare each actual result to your prediction.
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Repeat the same operation for each configured input so observations are comparable.
for size in (0,1,15,16,17):
data=b"x"*size
assert unpad(pad(data))==data
print(size,len(pad(data)))
## Experimental analysis and submission
1. Record the reference input, predicted output and actual result.
2. Modify one independent variable and run the relevant cells again.
3. Explain the result using the theory and identify model limitations.
4. Save the notebook with outputs and retain the separate theoretical worksheet.
**Your derivation and conclusion:**
(Complete independently.)
21Instructions · 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. ECB versus CBC — complete its numbered steps and record the requested evidence. 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.
Python implementation
Download the complete practical toolkit and extract it to a new directory. Keep the code and challenges folders together.
For the practical tasks, install PyCryptodome in your virtual environment. The included Python programs also support the cryptography library; the optional capstone uses cryptography.
Explore actual CPython execution traces from the included laboratory programs. Play, pause, step, inspect the current line, local variable values, function call stack, return values and output. Green variable cells changed relative to the preceding event. Line events show state before the highlighted line executes.
Run and visualize your own modified Python program
Download the Essential Cryptography Toolkit, extract it, and open a terminal in its code directory. Run the worked example or edit a copy. The trace generator executes your actual local Python file and creates an importable JSON record. Only run trusted code and use fictional keys and data.
Choose Import your trace in the visualizer and select my-trace.json. This works offline; the portal does not execute arbitrary Python on its server. The optional external Python Tutor link is suitable for standalone standard-library code, but external dependencies or local imports may not work.
For AES/DES exercises, install either supported cryptographic backend in an isolated Python environment as described in the Python code tab. Native library internals are not traced; the algorithm-specific browser workstations display the intermediate mathematics.
Why should authenticated encryption replace bare CBC for real deployments?
Submission: Submit ECB/CBC comparisons, alignment-error evidence, Base64 round trip, KDF settings and recovered training image. Never include real passwords or keys.
Export actual calculated observations from each workstation. Record your own predictions and conclusions, and distinguish browser calculations from local or physical measurements.
Shared research workbenches · network designer & advanced studiesConcurrent-device simulation & Monte Carlo research