Run actual bounded digest searches, construct HMAC from inner/outer hash pads and study keyed pseudo-random digit generation.
The focus of this experiment is to compare preimage, second-preimage and collision properties. Students then trace HMAC and keyed-generation inputs and outputs, and verify tags with controlled changes and distinguish hashes from encryption. 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 preimage, second-preimage and collision properties.
Trace HMAC and keyed-generation inputs and outputs.
Verify tags with controlled changes and distinguish hashes from encryption.
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 preimage, second-preimage and collision properties, trace HMAC and keyed-generation inputs and outputs, and verify tags with controlled changes and distinguish hashes from encryption.
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 tags with controlled changes and distinguish hashes from encryption. 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 AES modes — ECB, CBC, padding, password derivation and encrypted files.
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 Hash security — Preimages, collisions, HMAC and keyed generation
Run actual bounded digest searches, construct HMAC from inner/outer hash pads and study keyed pseudo-random digit generation.
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: Run actual bounded digest searches, construct HMAC from inner/outer hash pads and study keyed pseudo-random digit generation.
Complete the analytical preparation below before programming. Show the intermediate mathematical calculations.
Truncated preimage and collision search — complete its numbered steps and record the requested evidence.
Manual HMAC construction — complete its numbered steps and record the requested evidence.
Keyed digit generator — complete its numbered steps and record the requested evidence.
Reference check: Suffix searches show actual digest matches. Manual HMAC equals library HMAC for identical key/message/algorithm and fails when either input differs.
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. Truncated preimage and collision search — 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.
Message padding, word schedule, 80 compression rounds, chaining and final digest.
Preimages and collisions
A preimage search seeks an input that produces a specified digest value; a collision seeks two distinct inputs with equal digests. Truncating the digest to a few hexadecimal digits makes both experiments tractable. Vary the truncation length and repeat trials because the number of attempts is random.
HMAC construction
Normalize the key to the hash block length B: hash long keys and zero-pad shorter keys. SHA-256 has B=64 bytes and SHA-512 has B=128 bytes. HMAC computes H((K′ XOR opad) || H((K′ XOR ipad) || message)), where the byte patterns 0x5c and 0x36 are repeated B times.
Keyed digit generation
An HMAC-based state or counter can generate a reproducible stream under a classroom key. For decimal digits use rejection sampling: accept bytes below 250 then reduce modulo 10. Compare counts over repeated trials. This exercise is not a validated production DRBG.
Prerequisites: EC10 and earlier foundations as applicable.
Algorithm structure and data flow. Use the simulation to inspect the corresponding numerical transformations.
Engineering diagrams
Inner and outer hash inputs protect a keyed message.
Scientific foundations and worked examples
Security notions and work factors
For a fixed n-bit digest target, ideal preimage success after q independent attempts has probability 1−(1−\(2^{-n}\))^q; expected attempts are \(2^{n}\). A second-preimage task holds one original message fixed and seeks a different message with its digest. A collision allows both messages to vary; after q distinct messages its approximate probability is 1−exp(−q(q−1)/2^(n+1)). For an eight-bit suffix the average preimage effort is 256, while the 50% collision point is about 19 messages. Matching suffixes are not full SHA collisions.
SHA-512 preprocessing and schedule
Encode the message as bytes, append the 1 bit, then zeros until the length is 896 modulo 1024; append the original length as a 128-bit big-endian integer. Parse each padded block into sixteen 64-bit words \(W_{0}\)…\(W_{15}\). Expand to \(W_{79}\) using \(W_{t}\)=\(\sigma_{1}\)(\(W_{t-2}\))+\(W_{t-7}\)+\(\sigma_{0}\)(\(W_{t-15}\))+\(W_{t-16}\) modulo \(2^{64}\), where \(\sigma_{0}\)(x)=ROTR¹(x) XOR ROTR⁸(x) XOR SHR⁷(x), \(\sigma_{1}\)(x)=ROTR¹⁹(x) XOR ROTR⁶¹(x) XOR SHR⁶(x). SHA-512 processes 80 rounds per block using eight 64-bit working words.
Compression round and feed-forward
Define Ch(e,f,g)=(e AND f) XOR (NOT e AND g), Maj(a,b,c)=(a AND b) XOR (a AND c) XOR (b AND c). \(\Sigma_{0}\)(x)=ROTR²⁸(x) XOR ROTR³⁴(x) XOR ROTR³⁹(x), \(\Sigma_{1}\)(x)=ROTR¹⁴(x) XOR ROTR¹⁸(x) XOR ROTR⁴¹(x). At round t compute \(T_{1}\)=h+\(\Sigma_{1}\)(e)+Ch(e,f,g)+\(K_{t}\)+\(W_{t}\) and \(T_{2}\)=\(\Sigma_{0}\)(a)+Maj(a,b,c). Set (a,b,c,d,e,f,g,h)=(\(T_{1}\)+\(T_{2}\),a,b,c,d+\(T_{1}\),e,f,g), with additions modulo \(2^{64}\). After round 79 add the eight working words to the previous chaining value; the final digest concatenates the eight resulting words. The first block begins with the standardized IV; subsequent blocks use the previous feed-forward state.
HMAC and keyed generation
HMAC authenticates a message using a secret key and nested hashing. For SHA-512 the normalized key is 128 bytes; a 16-byte laboratory key receives 112 zero bytes. XOR the block with repeated 0x36 and 0x5C. The inner digest is 64 bytes, then the outer hash produces a 64-byte tag. Keys longer than the block are hashed before padding. A receiver independently computes the tag and compares it in constant time in real applications. For the classroom generator, HMAC(key,counter) produces deterministic bytes; hexadecimal symbols are direct nibbles, decimal digits require rejection of bytes 250–255 to avoid modulo bias. Uniform counts alone do not validate a cryptographic DRBG. Authentication does not supply confidentiality or replay protection.
SHA-512 architecture: from the padded 1024-bit block to the 512-bit digest.
Property
SHA-256
SHA-512
Block length
512 bits
1024 bits
Word length
32 bits
64 bits
Compression rounds
64
80
Digest length
256 bits
512 bits
HMAC block length
64 bytes
128 bytes
For abc, W0 = 6162638000000000 and W15 = 0000000000000018. The final SHA-512 digest is ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f.
Engineering principles · additional worked teaching example
A digest is unkeyed; HMAC authenticates data with a secret. For an ideal b-bit digest, expected collision-search scale is 2^(b/2) while preimage scale is 2^b. A toy 12-bit digest has 4096 possible outputs; birthday scale64.
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
Preimage resistance, second-preimage resistance and collision resistance have different challenges. For ideal n-bit output, generic collision search is about 2^(n/2) work, preimage about 2^n. HMAC keys the digest construction.
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 · Message
Message
Message
public telemetry
Hash
Message
public telemetry
Hash
unkeyed digest
HMAC
Message
public telemetry
Hash
unkeyed digest
HMAC
secret key + message
Verification
Message
public telemetry
Hash
unkeyed digest
HMAC
secret key + message
Verification
recompute tag; enforce freshness
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 is a preimage?
An input producing a specified digest.
What is a collision?
Distinct inputs with equal digests.
What does HMAC bind?
Message and secret key.
Why use truncated hashes in a search demo?
To make the search feasible; not production security.
Why truncate a digest for classroom experiments?
To make search demonstrations feasible without claiming a break of the full hash.
What is the expected work scale for an n-bit ideal preimage?
About 2^n trials.
What is the birthday collision work scale?
About 2^(n/2) trials.
What does HMAC add to hashing?
A secret key and structured inner/outer hashing.
What is the SHA-256 HMAC block size?
64 bytes.
What is the SHA-512 HMAC block size?
128 bytes.
What are the HMAC inner and outer pad constants?
0x36 and 0x5c respectively.
What should happen when a verification key changes?
Authentication should fail unless the resulting tag happens to match.
A receiver recomputes HMAC using a different key. What is expected?
Verification fails except for an extremely unlikely accidental tag match. Compare with a correct-key positive control.
For a 16-bit truncated digest, approximately how many random inputs give a 50% collision chance?
About sqrt(2 ln 2 × \(2^{16}\)) ≈301 distinct inputs under a uniform independent hash model.
What must be checked in addition to HMAC to reject a replayed packet?
A freshness policy such as an authenticated sequence number or nonce and a receiver replay window.
How many rounds does SHA-512 use per padded block?
80, operating on eight 64-bit working words.
How many bits encode the original message length in SHA-512 padding?
128, big-endian. The complete padded block length is a multiple of 1024.
What happens at 112 input bytes?
A second block is required because the 1-bit marker and 128-bit length field do not fit in the first block.
What are the two main temporary words in a SHA-512 compression round?
T1 combines h, Σ1, Ch, Kt and Wt; T2 combines Σ0 and Maj. All additions are modulo 2^64.
How is the new chaining value obtained?
Add each final working word to its corresponding incoming chaining word modulo 2^64.
For a 16-byte HMAC-SHA-512 key, how many zero bytes are appended?
112, bringing the normalized key to the 128-byte block length.
Does a collision in two hex digits imply a full SHA-512 collision?
No; it establishes only equality of the selected eight output bits.
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 · Preimage and collision probability
For one-hex-digit and two-hex-digit suffixes, derive expected fixed-target attempts and birthday-collision probabilities. Distinguish preimage, second preimage and collision.
Engineering method — A digest is unkeyed; HMAC authenticates data with a secret. For an ideal b-bit digest, expected collision-search scale is 2^(b/2) while preimage scale is 2^b. A toy 12-bit digest has 4096 possible outputs; birthday scale64. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
02 · HMAC calculation
For a 128-bit key and SHA-512, calculate the padded key length, ipad/opad lengths, inner/outer input lengths and tag size for an assigned message. Repeat for SHA-256. Write both nested-hash equations before testing.
Engineering method — A digest is unkeyed; HMAC authenticates data with a secret. For an ideal b-bit digest, expected collision-search scale is 2^(b/2) while preimage scale is 2^b. A toy 12-bit digest has 4096 possible outputs; birthday scale64. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
03 · Keyed generation
Explain HMAC(key,counter), convert bytes into hex digits, and derive an unbiased decimal extraction rule. Compare expected counts for one million samples; explain why empirical uniformity does not establish CSPRNG security.
Engineering method — A digest is unkeyed; HMAC authenticates data with a secret. For an ideal b-bit digest, expected collision-search scale is 2^(b/2) while preimage scale is 2^b. A toy 12-bit digest has 4096 possible outputs; birthday scale64. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
04 · SHA-512 compression
For abc, write the padded block layout, W0 and W15. Using the displayed round constants, calculate Ch, Maj, sigma functions, T1/T2 and the next state for one round. Verify after the hand calculation.
Engineering method — A digest is unkeyed; HMAC authenticates data with a secret. For an ideal b-bit digest, expected collision-search scale is 2^(b/2) while preimage scale is 2^b. A toy 12-bit digest has 4096 possible outputs; birthday scale64. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
05 · Security calculation
Security calculation · Independent work
Compare ideal 16-bit and 24-bit truncated digest birthday scales and preimage scales. Does a successful toy collision establish a full SHA-256 collision?
Security calculation — A digest is unkeyed; HMAC authenticates data with a secret. For an ideal b-bit digest, expected collision-search scale is 2^(b/2) while preimage scale is 2^b. A toy 12-bit digest has 4096 possible outputs; birthday scale64. 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 · EC11-01
For ideal 32-bit truncation compare generic preimage and collision scales.
Intermediate · Calculate or trace
Independent theoretical exercise · EC11-02
Two 8-bit digests 10101100 and 11000101 differ in how many bits?
Intermediate · Interpret the result
Independent theoretical exercise · EC11-03
Does a public SHA-256 digest of telemetry authenticate the sender?
Advanced · Analyze a condition
Independent theoretical exercise · EC11-04
HMAC tags are valid but repeated old messages are accepted. What control is missing?
Advanced · Diagnose or compare
Independent theoretical exercise · EC11-05
Why does hashing a file then comparing with a digest from the same untrusted source fail to establish authenticity?
Challenging · Engineering verification
Independent theoretical exercise · EC11-06
Design a classroom collision experiment with truncated hashes.
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.
Keyed digit generator — 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.
Derive the ideal preimage and collision probabilities; compare one- and two-hex-digit suffixes. For abc, derive the padding and \(W_{0}\)/\(W_{15}\) by hand; calculate one SHA-512 round with the inspector values, then explain HMAC key padding and rejection sampling.
Evidence: show the derivation, intermediate values and independent checks; explain any mismatch with the practical result.
SHA-512 experimental activity
Open Simulation and select SHA-512 compression microscope. Enter abc. Inspect padding, W0 through W79, round 0 T1/T2 and the eight working words; play through round 79 and feed-forward.
Change the input to an empty message, then 111 and 112 ASCII bytes. Record block counts and confirm the padding boundary. Compare the final digest with hashlib.sha512.
Select SHA-512 avalanche comparison. Compare I like cats and I like cars and record the bit distance.
Choose SHA-512 in the suffix and collision workstations, repeat with SHA-256 and hold the suffix width fixed. Record actual attempts. Repeat the HMAC and keyed generator with each hash.
Run python sha512_compare.py from the toolkit code folder; compare output with your simulation. Python comparison program.
Research question: Can a keyed tag detect message modification, and how does truncated digest size affect search?
Independent variables
Message, key, target suffix length, algorithm
Dependent observations
Attempts, digest, tag, verification result
Controls
Use fictional keys; change only message or receiver key; compare many bounded suffix searches if measuring effort.
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)
HMAC control
Same message and key
Verification succeeds
Enter observation
Tamper
Change one message character or key
Verification fails
Enter observation
Truncation
1 versus 2 hex-digit suffix
Expected search effort grows from 16 to 256 trials under uniform digest assumption; realized trials vary
Enter observation
Analysis: Distinguish full collision resistance from truncated matches. Report count and bounded search budget; compare manual HMAC with standard library.
Run actual bounded digest searches, construct HMAC from inner/outer hash pads and study keyed pseudo-random digit generation.
Equipment and execution
Browser-based simulator, Python 3, notebook or local evidence folder. Use WSL Setup only if you need a Linux runtime.
2. Follow these commands in sequence (Linux/WSL). For browser-only activities, open Simulation first; the code activities are independent.
BASH · Command
cd code
python lab11.py
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
Truncated preimage and collision search
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.
For the local toy digest search, count attempts to obtain each one-hex-digit suffix 0…f, then two-digit suffixes 00…ff using bounded trials; record exhaustion separately.
Search for any two distinct local candidate messages with equal last two digest digits. Compare effort with a fixed target suffix.
Use the animation to observe candidate counter, digest and match. Distinguish truncated matching from full hash attacks.
Evidence to record
Target, attempts, candidate(s), suffix and budget.
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
Manual HMAC construction
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 a fictional 128-bit key; choose SHA-512 for the 1024-bit padded-key task. Zero-pad to 128 bytes and construct ipad/opad XOR masks.
Compute H((K⊕opad)||H((K⊕ipad)||message)); compare with library HMAC as an independent check, not as the implementation.
Repeat SHA-256 with its 64-byte block size; change receiver key and message separately.
Evidence to record
Padded key size, inner digest, final tag, acceptance/rejection.
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
Keyed digit generator
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.
Build the educational keyed HMAC state generator with fictional key and seed; count hexadecimal output.
For decimal digits use rejection sampling (accept byte <250, reduce mod 10) rather than biased reduction of every byte. Compare counts/percentages.
Explain why this experiment is not a validated production DRBG; use a standard random generator in real applications.
Evidence to record
Hex/decimal histograms, rejection count and security limitations.
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
Suffix searches show actual digest matches. Manual HMAC equals library HMAC for identical key/message/algorithm and fails when either input differs.
Deliverables
Submit target-search and collision traces, HMAC intermediate values, successful and rejected authentication tests, and digit histograms.
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
# EC11 · Hash security — Preimages, collisions, HMAC and keyed generation
**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
Run actual bounded digest searches, construct HMAC from inner/outer hash pads and study keyed pseudo-random digit generation.
**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. Truncated preimage and collision search — complete its numbered steps and record the requested evidence.
3. Manual HMAC construction — complete its numbered steps and record the requested evidence.
4. Keyed digit generator — complete its numbered steps and record the requested evidence.
5. Compare observations with the reference checks and submit the required evidence.
**Evidence:** Suffix searches show actual digest matches. Manual HMAC equals library HMAC for identical key/message/algorithm and fails when either input differs.
**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. Truncated preimage and collision search — complete its numbered steps and record the requested evidence.
3. Manual HMAC construction — complete its numbered steps and record the requested evidence.
4. Keyed digit generator — 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
## 3. Algorithm implementation
Read each definition and relate it to the equations and scientific SVGs in Concepts.
05Instructions · Markdown
### Implementation cell 1
Inspect the definitions, then execute to make them available for the investigation.
06Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC11 | Code cell 01 | Hash security — Preimages, collisions, HMAC and keyed generation
# 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 11 — bounded teaching hash searches and manual HMAC construction."""
import hashlib,hmac,secrets
from collections import Counter
# Define the reusable operation find suffix; keep its logic separate from the trial.
def find_suffix(target,prefix='meter:',limit=100000,algorithm='sha256'):
if not 1<=len(target)<=2 or any(c not in '0123456789abcdef' for c in target): raise ValueError('Use one or two lowercase hex digits')
for i in range(limit):
candidate=(prefix+str(i)).encode(); digest=hashlib.new(algorithm,candidate).hexdigest()
if digest.endswith(target): return i+1,candidate,digest
raise RuntimeError('Search budget exhausted')
### Implementation cell 2
Inspect the definitions, then execute to make them available for the investigation.
08Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC11 | Code cell 02 | Hash security — Preimages, collisions, HMAC and keyed generation
# 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 truncated collision; keep its logic separate from the trial.
def truncated_collision(digits=2,limit=100000,algorithm='sha256'):
if not 1<=digits<=3: raise ValueError('Use 1–3 hex digits')
seen={}
for i in range(limit):
m=str(i).encode(); suffix=hashlib.new(algorithm,m).hexdigest()[-digits:]
if suffix in seen: return seen[suffix],m,suffix,i+1
seen[suffix]=m
raise RuntimeError('Search budget exhausted')
# Define the reusable operation manual hmac; keep its logic separate from the trial.
def manual_hmac(message,key,algorithm='sha512'):
size=hashlib.new(algorithm).block_size
if len(key)>size: key=hashlib.new(algorithm,key).digest()
key=key.ljust(size,b'\0'); ipad=bytes(v^0x36 for v in key); opad=bytes(v^0x5c for v in key)
inner=hashlib.new(algorithm,ipad+message).digest()
return hashlib.new(algorithm,opad+inner).digest()
# Define the reusable operation keyed digits; keep its logic separate from the trial.
def keyed_digits(key,count,decimal=True,algorithm='sha256'):
parts=[]; length=0; i=0
while length<count:
d=manual_hmac(f'counter:{i}'.encode(),key,algorithm); i+=1
p=''.join(str(x%10) for x in d if x<250) if decimal else d.hex()
parts.append(p); length+=len(p)
return ''.join(parts)[:count]
## 4. Execute reference controls
The program checks selected algorithm outcomes. Record the observed output. These checks do not replace the independent calculation assignment.
10Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC11 | Code cell 03 | Hash security — Preimages, collisions, HMAC and keyed generation
# 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.
# =====================================================================
# Prepare key; retain only the scope required for this trial.
key = secrets.token_bytes(16)
# Set msg for the next computation or reference condition.
msg = b'Temperature=25'
# Repeat the same operation for each configured input so observations are comparable.
for alg in ('sha256', 'sha512'):
assert manual_hmac(msg, key, alg) == hmac.digest(key, msg, alg)
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert not hmac.compare_digest(manual_hmac(msg, key), manual_hmac(b'Temperature=26', key))
print('Suffix result:', find_suffix('00'))
print('Truncated collision:', truncated_collision())
print(Counter(keyed_digits(key, 10000)))
## 5. Controlled variation
Predict the effect of the parameter changes below. Compare each actual result to your prediction.
12Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC11 | Code cell 04 | Hash security — Preimages, collisions, HMAC and keyed generation
# 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,manual_hmac(b"Temperature=25",b"classroom-key",algorithm).hex())
assert manual_hmac(b"Temperature=25",b"classroom-key",algorithm)!=manual_hmac(b"Temperature=26",b"classroom-key",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.)
14Instructions · 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. Truncated preimage and collision search — 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.
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 is finding a suffix collision easier than a full SHA-256 collision?
Why does HMAC-SHA-512 pad to 128 bytes?
How does rejection sampling avoid decimal modulo bias?
Submission: Submit target-search and collision traces, HMAC intermediate values, successful and rejected authentication tests, and digit histograms.
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