Use a cryptography library to encrypt a byte stream, inspect SHA-256/SHA-512 digests and investigate deterministic hash-chain pseudo-randomness.
The focus of this experiment is to use cryptographic library APIs for AES-CTR and hashing. Students then trace nonce/counter uniqueness and deterministic hash-chain evolution, and verify recovery and distinguish classroom generator from secure OS randomness. 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
Use cryptographic library APIs for AES-CTR and hashing.
Trace nonce/counter uniqueness and deterministic hash-chain evolution.
Verify recovery and distinguish classroom generator from secure OS randomness.
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 use cryptographic library APIs for AES-CTR and hashing, trace nonce/counter uniqueness and deterministic hash-chain evolution, and verify recovery and distinguish classroom generator from secure OS randomness.
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 recovery and distinguish classroom generator from secure OS randomness. 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 Hash security — Preimages, collisions, HMAC and keyed generation.
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 PyCryptodome — AES-CTR, hashing and hash-chain PRNG
Use a cryptography library to encrypt a byte stream, inspect SHA-256/SHA-512 digests and investigate deterministic hash-chain pseudo-randomness.
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: Use a cryptography library to encrypt a byte stream, inspect SHA-256/SHA-512 digests and investigate deterministic hash-chain pseudo-randomness.
Complete the analytical preparation below before programming. Show the intermediate mathematical calculations.
PyCryptodome CTR file format — complete its numbered steps and record the requested evidence.
SHA-256 and SHA-512 — complete its numbered steps and record the requested evidence.
Hash-chain digit generation and timing — complete its numbered steps and record the requested evidence.
Reference check: SHA-256("I like cats") = 446b43a682a92a039e4081a30be1c39c7d46b3675d6e209c200a252c410167d9. Correct CTR decryption recovers all bytes; seed stream matches the reference.
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. PyCryptodome CTR file format — 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.
Counter mode encrypts a unique nonce/counter input to obtain a keystream, then XORs it with plaintext. Decryption uses the same keystream; store the nonce alongside ciphertext. Never repeat a nonce/counter sequence under the same key. CTR by itself does not authenticate data.
Digest properties
SHA-256 and SHA-512 map byte strings to 32 and 64 bytes respectively. Hexadecimal representations use twice as many characters. Compare the exact digest and Hamming distance after changing one input character; similar messages should not imply similar digests.
Iterated hash generation
Hash a seed, retain binary digest as the next state and collect the desired hexadecimal output. Compare one-digit extraction against full-digest extraction with equal output counts. A frequency histogram can detect some bias but cannot establish cryptographic unpredictability; a public seed makes this generator predictable.
Prerequisites: EC09 and earlier foundations as applicable.
Algorithm structure and data flow. Use the simulation to inspect the corresponding numerical transformations.
Engineering diagrams
CTR uses encrypted counter blocks as a keystream.
Scientific foundations and worked examples
CTR keystream construction
For AES-CTR, encrypt a distinct 128-bit nonce/counter block with the key and XOR the resulting 16-byte keystream with data. A partial final block uses only the needed keystream bytes; no padding is required. The receiver reconstructs the same counter sequence. The nonce is not secret, but it must not be reused with the same key. The laboratory stores nonce bytes before ciphertext; the decoder must know their length.
SHA-256 and SHA-512 digest experiment
A digest is deterministic and has fixed width independent of message length. SHA-256 produces 32 bytes (64 hex digits), SHA-512 produces 64 bytes (128 hex digits). Compare the exact UTF-8 strings I like cats and I like cars. The expected difference is a statistical avalanche property, not a guaranteed exact half of bits for each pair. Measure bitwise Hamming distance, not merely the count of changed hex symbols.
Hash-chain generation and performance
Let \(s_{0}\) be the byte encoding of the seed, then \(s_{i+1}\)=H(\(s_{i}\)). The next state is the binary digest, not its printed hexadecimal text. The final hex digit of each digest gives one output symbol; consuming all 64 SHA-256 hex digits reduces the number of hash calls for one million digits from 1,000,000 to 15,625. SHA-512 needs ceil(1,000,000/128)=7,813 calls. Compare elapsed time under identical conditions; fewer calls does not guarantee proportional speedup. Uniform-looking histograms do not establish unpredictability, and public state allows future outputs to be computed.
Engineering principles · additional worked teaching example
CTR uses an encrypted nonce/counter as a keystream; plaintext XOR stream gives ciphertext and XOR again recovers. If a teaching keystream byte is A5 and message 3C, ciphertext99. Reusing stream exposes XOR of messages; hash-chain output alone is not a complete secure generator.
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
AES-CTR produces a keystream from nonce/counter blocks; XOR makes encryption and decryption symmetric. Hash chains iterate a digest but a public deterministic chain is not a secure RNG.
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 · Counter block
Counter block
Counter block
nonce concatenated with counter
AES encryption
Counter block
nonce concatenated with counter
AES encryption
keystream K
XOR
Counter block
nonce concatenated with counter
AES encryption
keystream K
XOR
35 XOR C2 = F7
Recover
Counter block
nonce concatenated with counter
AES encryption
keystream K
XOR
35 XOR C2 = F7
Recover
F7 XOR C2 = 35
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 explanationsWhy must CTR counters not repeat under a key?
Keystream reuse reveals plaintext relationships.
Does CTR alone authenticate?
No.
What does SHA-256 output?
A 256-bit digest.
Why not use a simple hash chain as a production RNG?
It lacks vetted entropy and state-security design.
How does CTR generate a keystream?
Encrypt unique counter blocks under the key.
How does CTR encrypt plaintext?
XOR plaintext with keystream bytes.
Why must the nonce/counter never repeat under a key?
Repetition reuses keystream and exposes relationships between messages.
Does CTR need block padding?
No, it can use a partial final keystream block.
Does CTR provide authentication by itself?
No.
How long is SHA-256 output?
256 bits, or 32 bytes.
How long is SHA-512 output?
512 bits, or 64 bytes.
What changes when a message character changes?
Its digest typically changes in many bit positions.
How does a hash chain generate another state?
Hash the preceding state according to the specified encoding.
Why control message length when benchmarking?
To compare equivalent workloads.
Two AES-CTR blocks reuse the same counter under one key. What is the risk?
The keystream repeats. XORing ciphertexts reveals the XOR of the plaintexts at repeated positions.
Can a SHA-256 digest decrypt its original input?
No. A digest is a fixed-length one-way fingerprint, not encryption.
How should SHA-256 and SHA-512 timing be compared?
Use the same input bytes, environment and repetitions, recording elapsed time and message length.
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 · CTR
Sketch two AES counter blocks and their keystream XORs. Derive decryption; calculate nonce/counter and ciphertext lengths for a partial block. Explain nonce reuse.
Engineering method — CTR uses an encrypted nonce/counter as a keystream; plaintext XOR stream gives ciphertext and XOR again recovers. If a teaching keystream byte is A5 and message 3C, ciphertext99. Reusing stream exposes XOR of messages; hash-chain output alone is not a complete secure generator. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
02 · SHA comparison
For I like cats and I like cars, predict digest lengths in bytes and hex digits; explain why the number of changed bits is not fixed. Compute Hamming distance after independent hash verification.
Engineering method — CTR uses an encrypted nonce/counter as a keystream; plaintext XOR stream gives ciphertext and XOR again recovers. If a teaching keystream byte is A5 and message 3C, ciphertext99. Reusing stream exposes XOR of messages; hash-chain output alone is not a complete secure generator. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
03 · Hash-chain output
Describe the binary state update and last-nibble extraction for seed 20241127. Compare one-nibble and whole-digest extraction; calculate required hash calls for one million hex digits using SHA-256 and SHA-512. Explain why uniform counts do not prove unpredictability.
Engineering method — CTR uses an encrypted nonce/counter as a keystream; plaintext XOR stream gives ciphertext and XOR again recovers. If a teaching keystream byte is A5 and message 3C, ciphertext99. Reusing stream exposes XOR of messages; hash-chain output alone is not a complete secure generator. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
04 · Security reasoning
Security reasoning · Independent work
Given plaintext bytes 0x10,0x23 and illustrative distinct stream bytes 0x8F,0x55, derive ciphertext; describe risk if the exact stream is reused with another message.
Security reasoning — CTR uses an encrypted nonce/counter as a keystream; plaintext XOR stream gives ciphertext and XOR again recovers. If a teaching keystream byte is A5 and message 3C, ciphertext99. Reusing stream exposes XOR of messages; hash-chain output alone is not a complete secure generator. 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 · EC10-01
Given P=0x35 and stream 0xC2, calculate C and recover.
Intermediate · Calculate or trace
Independent theoretical exercise · EC10-02
A counter starts at 10 and processes five blocks. List counters.
Intermediate · Interpret the result
Independent theoretical exercise · EC10-03
What happens if a nonce/counter pair is reused under the same key?
Advanced · Analyze a condition
Independent theoretical exercise · EC10-04
Hash output is 256 bits. How many hexadecimal characters represent it?
Advanced · Diagnose or compare
Independent theoretical exercise · EC10-05
Does hashing a public predictable counter make its output unpredictable to an observer?
Challenging · Engineering verification
Independent theoretical exercise · EC10-06
Design a local verification of CTR correctness and integrity.
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.
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.
Derive the CTR inverse equation and show why keystream reuse leaks XORs. Calculate digest lengths and the exact iteration counts for one million hexadecimal digits. Predict the effect of replacing one character.
Evidence: show the derivation, intermediate values and independent checks; explain any mismatch with the practical result.
Practical laboratory manual
Scientific experimental protocol
Research question: What do nonce handling, hash diffusion and hash-chain output selection change?
Use fixed demo key for local CTR comparison only; compare identical message and seed for algorithm comparisons.
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)
CTR
Unique nonce and same demo key
Decrypt exact original bytes
Enter observation
Digest
SHA-256 versus SHA-512
32 versus 64 bytes
Enter observation
Hash-chain fixture
Seed 20241127, first ten hex digits under reference method
94a42c79e4
Enter observation
Analysis: Record histogram and sample size; timing is machine-dependent. A balanced histogram is not evidence of cryptographic unpredictability.
Use a cryptography library to encrypt a byte stream, inspect SHA-256/SHA-512 digests and investigate deterministic hash-chain pseudo-randomness.
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
PyCryptodome CTR file format
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.
Install pycryptodome in the lab environment. Run the AES-CTR program with secret data to transmit and generated 16-byte demo key.
Inspect encrypted.bin as nonce followed by ciphertext. Record actual nonce length, read it back, construct AES.MODE_CTR with the same key and nonce, and decrypt.
Repeat with a fresh nonce; verify identical plaintext recovery. Explain that CTR alone has no integrity tag.
Evidence to record
Envelope offsets and byte-for-byte round trip.
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
SHA-256 and SHA-512
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.
Hash I like cats using both PyCryptodome functions and compare with the exact provided digest values below.
Record output byte and hex lengths, then hash I like cars and compute differing digest bits.
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
Hash-chain digit generation and timing
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 seed 20241127 and SHA-256; feed binary digest back as state and take final hexadecimal digit. Check the first ten digits 94a42c79e4.
Generate 1,000,000 digits with a fictional seed, count all 16 symbols and percentages. Compare with extracting all 64 hex digits per SHA-256 digest (15,625 calls).
Repeat using SHA-512 (128 hex digits per digest, truncate final output to exactly 1,000,000). Compare SHA-256 and SHA-512 under identical conditions.
Use time.time or perf_counter on the same machine and identical sample count; report repetitions, histogram and runtime. Explain why uniformity is not proof of cryptographic security.
Evidence to record
Seed encoding, first ten digits, counts, percentages, timing table.
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.
Verification criteria
SHA-256("I like cats") = 446b43a682a92a039e4081a30be1c39c7d46b3675d6e209c200a252c410167d9. Correct CTR decryption recovers all bytes; seed stream matches the stated check.
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
# EC10 · PyCryptodome — AES-CTR, hashing and hash-chain PRNG
**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
Use a cryptography library to encrypt a byte stream, inspect SHA-256/SHA-512 digests and investigate deterministic hash-chain pseudo-randomness.
**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. PyCryptodome CTR file format — complete its numbered steps and record the requested evidence.
3. SHA-256 and SHA-512 — complete its numbered steps and record the requested evidence.
4. Hash-chain digit generation and timing — complete its numbered steps and record the requested evidence.
5. Compare observations with the reference checks and submit the required evidence.
**Evidence:** SHA-256("I like cats") = 446b43a682a92a039e4081a30be1c39c7d46b3675d6e209c200a252c410167d9. Correct CTR decryption recovers all bytes; seed stream matches the reference.
**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. PyCryptodome CTR file format — complete its numbered steps and record the requested evidence.
3. SHA-256 and SHA-512 — complete its numbered steps and record the requested evidence.
4. Hash-chain digit generation and timing — 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
# =====================================================================
# EC10 | Code cell 01 | PyCryptodome — AES-CTR, hashing and hash-chain PRNG
# 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()
# =====================================================================
# EC10 | Code cell 02 | PyCryptodome — AES-CTR, hashing and hash-chain PRNG
# 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]
# =====================================================================
# EC10 | Code cell 03 | PyCryptodome — AES-CTR, hashing and hash-chain PRNG
# 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
# =====================================================================
# EC10 | Code cell 04 | PyCryptodome — AES-CTR, hashing and hash-chain PRNG
# 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 10 — AES-CTR file layout, digest avalanche and hash-chain PRNG."""
import hashlib,secrets,time
from collections import Counter
from pathlib import Path
from crypto_backend import aes_crypt,BACKEND
# Define the reusable operation encrypted envelope; keep its logic separate from the trial.
def encrypted_envelope(message,key,nonce): return nonce+aes_crypt(key,message,'CTR',nonce)
### Implementation cell 2
Inspect the definitions, then execute to make them available for the investigation.
15Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC10 | Code cell 05 | PyCryptodome — AES-CTR, hashing and hash-chain PRNG
# 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 decrypt envelope; keep its logic separate from the trial.
def decrypt_envelope(envelope,key):
if len(envelope)<8: raise ValueError('Missing nonce prefix')
return aes_crypt(key,envelope[8:],'CTR',envelope[:8],True)
# Define the reusable operation hash digits; keep its logic separate from the trial.
def hash_digits(seed,n,algorithm='sha256',all_digits=False):
state=seed.encode(); pieces=[]; count=0
while count<n:
state=hashlib.new(algorithm,state).digest(); h=state.hex() if all_digits else state.hex()[-1]
pieces.append(h); count+=len(h)
return ''.join(pieces)[:n]
## 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
# =====================================================================
# EC10 | Code cell 06 | PyCryptodome — AES-CTR, hashing and hash-chain PRNG
# 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.
# =====================================================================
import argparse
# Set p for the next computation or reference condition.
p = argparse.ArgumentParser()
p.add_argument('--digits', type=int, default=10000)
p.add_argument('--write-demo', type=Path)
# Set args for the next computation or reference condition.
args = p.parse_args([])
if not 1 <= args.digits <= 1000000:
p.error('Use 1–1,000,000 digits')
# Prepare key; retain only the scope required for this trial.
key = secrets.token_bytes(16)
# Prepare nonce; retain only the scope required for this trial.
nonce = secrets.token_bytes(8)
# Set msg for the next computation or reference condition.
msg = b'secret data to transmit'
# Set data for the next computation or reference condition.
data = encrypted_envelope(msg, key, nonce)
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert decrypt_envelope(data, key) == msg
if args.write_demo:
args.write_demo.write_bytes(data)
print('Fictional demo key (hex):', key.hex())
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert hashlib.sha256(b'I like cats').hexdigest() == '446b43a682a92a039e4081a30be1c39c7d46b3675d6e209c200a252c410167d9'
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert hash_digits('20241127', 10) == '94a42c79e4'
# Repeat the same operation for each configured input so observations are comparable.
for algorithm in ('sha256', 'sha512'):
for all_digits in (False, True):
start = time.perf_counter()
out = hash_digits('20241127', args.digits, algorithm, all_digits)
elapsed = time.perf_counter() - start
print(algorithm, all_digits, 'seconds', round(elapsed, 4), 'histogram', dict(sorted(Counter(out).items())))
print('Backend:', BACKEND, '— local reference checks passed')
## 5. Controlled variation
Predict the effect of the parameter changes below. Compare each actual result to your prediction.
19Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC10 | Code cell 07 | PyCryptodome — AES-CTR, hashing and hash-chain PRNG
# 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 algorithm in ("sha256","sha512"):
print(algorithm,hash_digits("20241127",40,algorithm))
## 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. PyCryptodome CTR file format — 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.
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