Encrypt and decrypt paired messages using four classical ciphers and analyze their statistical weaknesses.
The focus of this experiment is to trace Playfair digraph preparation and polyalphabetic key streams. Students then calculate encryption and inverse operations with explicit conventions, and compare frequency evidence and explain why historical ciphers are not secure. 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
Trace Playfair digraph preparation and polyalphabetic key streams.
Calculate encryption and inverse operations with explicit conventions.
Compare frequency evidence and explain why historical ciphers are not secure.
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 trace Playfair digraph preparation and polyalphabetic key streams, calculate encryption and inverse operations with explicit conventions, and compare frequency evidence and explain why historical ciphers are not secure.
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 compare frequency evidence and explain why historical ciphers are not secure. 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 Modular arithmetic I — Congruences and residues.
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 Historical ciphers II — Playfair, Vigenère, Autokey and frequency analysis
Encrypt and decrypt paired messages using four classical ciphers and analyze their statistical weaknesses.
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: Encrypt and decrypt paired messages using four classical ciphers and analyze their statistical weaknesses.
Complete the analytical preparation below before programming. Show the intermediate mathematical calculations.
Playfair digraphs and peer exchange — complete its numbered steps and record the requested evidence.
Monoalphabetic substitution, Vigenère and Autokey — complete its numbered steps and record the requested evidence.
Classical ciphertext analysis — complete its numbered steps and record the requested evidence.
Reference check: Valid Playfair output round-trips to the prepared digraph text; Vigenère, Autokey and monoalphabetic substitution recover normalized plaintext with the correct key.
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. Playfair digraphs and peer exchange — 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 concepts and engineering principles
Scientific architecture · EC02 · Historical ciphers II — Playfair, Vigenère, Autokey and frequency analysis
Playfair fills a 5×5 square with unique keyword letters followed by unused letters, merging I/J. Split the normalized text into pairs, inserting a filler between repeated letters and at the end if required. For encryption shift along the same row or column, or use the opposite rectangle corners. Reverse the shifts for decryption.
Repeating and adaptive key streams
Vigenère adds key-letter indices modulo 26. Autokey starts from the keyword and extends it with plaintext rather than repeating the keyword. Decryption reconstructs the stream incrementally. A fixed substitution maps equal symbols identically; a position-dependent stream does not necessarily do so.
Quantitative cryptanalysis
Calculate symbol counts and relative frequencies, then compare repeated n-grams and their spacings. A candidate substitution must remain bijective and explain the entire message. For Vigenère, estimate period from repeated spacings and compare each residue class of positions. Perform these analyses only on the supplied classroom ciphertext data.
Prerequisites: EC01 and earlier foundations as applicable.
Algorithm structure and data flow. Use the simulation to inspect the corresponding numerical transformations.
Engineering diagrams
A varying key produces varying shifts.
Scientific foundations and worked examples
Playfair geometry and normalization
Construct the square by deleting repeated keyword letters, merging I/J, then appending unused letters. BALLOON yields rows BALON, CDEFG, HIKMP, QRSTU, VWXYZ. With this square the pair ME lies in a rectangle and maps to KF. Compute by coordinates: M is row 2 column 3 and E is row 1 column 2 (zero-based); the exchanged corners are K and F. Same-row pairs shift right and same-column pairs down; decryption reverses these shifts. Split repeated letters using an agreed filler and document whether the original I/J distinction can be recovered.
Monoalphabetic, Vigenère and Autokey
A monoalphabetic substitution preserves the counts of symbols up to relabeling. Vigenère adds a repeated key index to each plaintext index modulo 26. For HELLO and BUCK the repeated key stream is BUCKB, yielding IYNVP. Autokey appends the plaintext to the initial key, so the stream BUCKH yields IYNVV. During decryption recovered plaintext extends the key stream; errors can propagate to later positions.
Frequency, n-grams and known plaintext
The count of a letter divided by the total letter count gives its relative frequency. Compare these counts with the language model; frequent bigrams and trigrams add context when spaces are removed. For a repeating key, distances between repeated ciphertext groups can suggest a common period through their factors. A candidate key length is then tested by splitting the ciphertext into position classes. In a known-plaintext Autokey exercise, subtract aligned known plaintext indices from ciphertext indices modulo 26 to infer the corresponding key-stream positions. Confirm a candidate by re-encryption.
Engineering principles · additional worked teaching example
Vigenère applies cyclic key letters as modular shifts; with plaintext HI and key BC (1,2), H→I and I→K. Playfair uses digraph transformations and a 5×5 grid; its padding and I/J convention must be specified. Autokey extends key using message symbols, not merely repetition.
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
Vigenère adds successive key indices modulo 26; Playfair operates on pairs of letters using a 5×5 square. A repeated Vigenère key has a period and may expose structure. Example: AB + BC = BD.
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 indices
Plaintext indices
Plaintext indices
A B = 0,1
Key indices
Plaintext indices
A B = 0,1
Key indices
B C = 1,2
Add modulo 26
Plaintext indices
A B = 0,1
Key indices
B C = 1,2
Add modulo 26
1,3 → BD
Subtract key
Plaintext indices
A B = 0,1
Key indices
B C = 1,2
Add modulo 26
1,3 → BD
Subtract key
0,1 → AB
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 explanationsHow does Playfair process text?
Pairs of letters use a keyed matrix and row, column or rectangle rules.
How does Vigenère differ from Caesar?
It varies shifts using a repeating key.
What does Autokey change?
It extends the key with message-derived characters.
What does Kasiski estimate?
Repeating-key period from repeated ciphertext distances.
Why is a Playfair key matrix 5 by 5?
It represents 25 symbols, usually combining I and J.
What happens to duplicate key letters?
Keep the first occurrence and skip repeats.
What is a Playfair digraph?
A pair of plaintext letters processed together.
How are letters in the same row encrypted?
Move each one right, wrapping around.
How are letters in the same column encrypted?
Move each one down, wrapping around.
How is a rectangle digraph encrypted?
Keep each row and exchange the columns.
Why use filler letters?
To separate repeated letters in a pair and complete an odd-length message.
How does Autokey extend the key?
It extends an initial secret with plaintext symbols.
What does Kasiski analysis use?
Distances between repeated ciphertext fragments to suggest key lengths.
A Playfair pair lies in the same row. What is its encryption rule?
Replace each symbol with its neighbor to the right, wrapping at the row boundary. Use the agreed preprocessing convention.
A Vigenère key repeats every five symbols. What feature can repeated ciphertext n-grams suggest?
Distances between repeated n-grams may be multiples of the period; they are clues, not proof. Compare several distances and candidate periods.
Why does repeated-letter preprocessing matter for Playfair?
A pair of identical letters needs a filler under the chosen convention. The decryptor must interpret fillers consistently.
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 · Playfair
Construct the 5 × 5 POTATO key square. Choose a message, document digraph preparation and calculate each ciphertext pair. Exchange the ciphertext with a partner and recover their plaintext.
Engineering method — Vigenère applies cyclic key letters as modular shifts; with plaintext HI and key BC (1,2), H→I and I→K. Playfair uses digraph transformations and a 5×5 grid; its padding and I/J convention must be specified. Autokey extends key using message symbols, not merely repetition. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
02 · Substitution
Construct a bijective alphabet mapping. Encrypt and decrypt a peer message; tabulate each input/output symbol.
Engineering method — Vigenère applies cyclic key letters as modular shifts; with plaintext HI and key BC (1,2), H→I and I→K. Playfair uses digraph transformations and a 5×5 grid; its padding and I/J convention must be specified. Autokey extends key using message symbols, not merely repetition. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
03 · Vigenère
Using POTATO, align each message letter with its repeated key letter. Calculate encryption and decryption modulo 26; verify a peer ciphertext.
Engineering method — Vigenère applies cyclic key letters as modular shifts; with plaintext HI and key BC (1,2), H→I and I→K. Playfair uses digraph transformations and a 5×5 grid; its padding and I/J convention must be specified. Autokey extends key using message symbols, not merely repetition. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
04 · Autokey
Use POTATO as the initial key and extend it with plaintext. Write the complete key stream and decrypt the partner ciphertext sequentially.
Engineering method — Vigenère applies cyclic key letters as modular shifts; with plaintext HI and key BC (1,2), H→I and I→K. Playfair uses digraph transformations and a 5×5 grid; its padding and I/J convention must be specified. Autokey extends key using message symbols, not merely repetition. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
05 · Cryptanalysis
For each of the four assigned ciphertext challenges already in the procedure, calculate letter frequencies or repeated n-gram distances as appropriate. Record proposed mappings/key periods and demonstrate re-encryption of a candidate plaintext.
Engineering method — Vigenère applies cyclic key letters as modular shifts; with plaintext HI and key BC (1,2), H→I and I→K. Playfair uses digraph transformations and a 5×5 grid; its padding and I/J convention must be specified. Autokey extends key using message symbols, not merely repetition. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
06 · Trace
Trace · Independent work
Use A=0 and repeated key KEY to encrypt CAT. Give the shifts and inverse calculation.
Trace — Vigenère applies cyclic key letters as modular shifts; with plaintext HI and key BC (1,2), H→I and I→K. Playfair uses digraph transformations and a 5×5 grid; its padding and I/J convention must be specified. Autokey extends key using message symbols, not merely repetition. 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 · EC02-01
With A=0, encrypt CAT using repeating key DOG.
Intermediate · Calculate or trace
Independent theoretical exercise · EC02-02
Decrypt LXF under key KEY.
Intermediate · Interpret the result
Independent theoretical exercise · EC02-03
A Playfair square puts A and B in the same row, with C immediately right of B. For pair AB, what are outputs under right-shift encryption?
Advanced · Analyze a condition
Independent theoretical exercise · EC02-04
Why must repeated letters in a Playfair digraph be split according to a stated filler convention?
Advanced · Diagnose or compare
Independent theoretical exercise · EC02-05
For a repeated key of length 3, which positions share a key letter among positions 1–9?
Challenging · Engineering verification
Independent theoretical exercise · EC02-06
Compare Vigenère with plaintext-autokey for an initial three-letter key and a one-symbol error.
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.
Construct the BALLOON matrix and calculate ME by hand. Compare the full HELLO/BUCK Vigenère and Autokey streams. Explain what a repeated bigram can and cannot establish.
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 cipher rules and key streams affect recovery and statistical leakage?
Independent variables
Cipher, keyword, candidate substitution
Dependent observations
Prepared digraphs, ciphertext, frequency distribution, recovered message
Controls
Use the same normalized plaintext when comparing Vigenère and Autokey; preserve the cipher-specific filler rules.
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.
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 lab02.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
Playfair digraphs and peer 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.
Build the BALLOON example matrix by removing repeated keyword letters, combining I/J and filling remaining letters. Work through the worked plaintext Meetings tomorrow and decrypt rdpktxtpto; check the row, column and rectangle rules with the simulator.
Rebuild the matrix using POTATO. Choose a fictional message, prepare digraphs (insert filler for repeated letters and odd length), encrypt and send only the ciphertext to a lab partner.
Decrypt your partner’s ciphertext with the POTATO matrix. Record the normalized plaintext separately from interpreted filler/I-J choices.
Evidence to record
Matrix, prepared digraphs, outgoing and incoming ciphertext, recovered text.
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
Monoalphabetic substitution, Vigenère and Autokey
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.
Construct a bijective substitution key; use the meet example below as a mapping check, then exchange an encrypted fictional message and key.
Use HELLO/BUCK to inspect repeated-key Vigenère indexing. Repeat using POTATO, align the repeating keyword and decrypt a partner’s message.
For Autokey, append plaintext symbols to the initial POTATO keyword instead of repeating it. Recover the key stream during decryption and compare it with Vigenère.
For the substitution check, map the alphabet abcdefghijklmnopqrstuvwxyz to dkvqfibjwpescxhtmyaoulrgzn. Encrypt meet and invert the mapping; compare with cffu.
Evidence to record
One key stream or mapping and two-way exchange per cipher.
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
Classical ciphertext analysis
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 the local frequency-analysis workstation to inspect the substitution challenges below, first with preserved spaces then without. For the first external exercise use the named educational frequency-analysis tool or your local equivalent.
Count single letters and n-grams, hypothesize substitutions, update the candidate mapping, and check whether the same mapping explains all repeated patterns.
For the Vigenère ciphertext estimate key length using repeated n-grams/Kasiski and compare frequency distributions of each column; test candidate keys.
For the Autokey challenge use the ciphertext and an initial-key hypothesis; do not treat an unverified readable fragment as proof.
Record candidate keys, full reconstructed text, and verification by re-encryption; keep unresolved cases marked unresolved.
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.
04
Python frequency analysis (bonus)
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.
Read a local text file. Count alphabetic characters case-sensitively, then merge uppercase and lowercase.
Compare the two histograms and check that the total count is preserved.
Evidence to record
Submit both frequency tables and the Python program.
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
Substitution with spaces: YIF QFMZRW QFYV ECFMD ZPCVMRZW NMD ZVEJB TXCDD UMJN DIFEFMDZ CD MQ ZKCEYFCJMYR NCW JCSZR EXCHZ UNMXZ NZ UCDRJ XYYSMRT M EYIFZW DYVZ VYFZ GIMHZ CRW NZ DZJJXZW ACHS MR NMD HNCMF QCHZ JMXJZW IE JYUCFWD JNZ DIR
Substitution without spaces: ljfbyzlyhudziwfbyiwfltrwhcljulehwsyuwjliedqfwjfqdhyljljfqdugtljaljulwjjgiyqwhrfdfbylrhwiltndqhuwjurgxrypgyjfhsqyhwxyhyuwrwqwxltjgiyqwhrfdfbytbqlrflwjndqhuwhdjanlfbwhcbnwqlvilwhcljulnwrwhrddjydzfbyzwfbyqrdztqsefdaqwebsxglhuljadjfbyndqcdzwhcbwhlhwhcljulrxddcyjflfhyuiwjgrtqlefdjuytlebyqljatqsefdaqwebltiyrrwayrawkyqlryfdfbyxlqfbdztqsefwjwhsrlrnwrfbyywqhlyrfcjdnjgrydzrfwflrfltwhljzyqyjtywjuljfqdugtyurykyqwhjyniyfbdurdzxqywcljatlebyqrjdfwxhszqypgyjtswjwhsrlrgrljablriwfbyiwfltwhwjuiyultwhyoeyqflrybynwrwxhyfduykyhdewrtwhyfbwfndghuwhhdnudtfdqrfdpgwjflzsfbyedfyjtsdzfbylqiyultwfldj
Vigenère: d cathrclwaec ls cfb ohxhnuaye osqewnhr vzdt vsugglv cqesuvwu ipxrroswiqf vyulhmu, urmrmwet fhtyguku, aqftsvttmftwjhs, qj setkrncd foohxtgj gexafeu. sq avldcmwu iu s setkrn qj srquhsu lkav swtgestu lr aeuhsu vdtc, xxnellopk, rr qlket jhsvjlcvwg atwds qx whg kbsvwp wklkowl duvzrrkrdtkgq, pqlhnvadlnq zivz panafiqmv iplhnv. vhpgfgipy rn vzh cqfwezl, fydwuavldcmk fap th pcjw oh ubbgj zatxdrg gu cathrvwurqjlso. s fydwuavldcm udn dw hmrdrygv ey ugyetwlgp kwavwv, ipvlvkvxank, jrqmss, ugfiglb ot gugcflscllopk dnf aw mcq rrkylnclh ftgp ap sqopqpowk vowjfe. c huofmft vzdt hsfinawavwv a eqeetswtcun iu krmgllmgk fandhd c ubbgj zechrn.
Autokey: ifmsfcxeicnkoghhdosqcyrmbaymnovoxwtkxbtioycqleeyyerbwzwxabxzyerdlpbywbipxbakugblxaleixxqrjqwrwxovglxlbefsglshvcpbqgaswsxiithukeomrptuczuadkjcdbyfgagecqvsjfmkkzhscobhmdvsptmazbuhlghngekqhhnvrzunmwmrwaujtlgphvtnqfzqbkmcbfmwndpsxvhngstnlixbpgryhymilzwblykrwzmedjiszfctvflfrontsngnzaccghwiylmjaucntfgbajipszfopqsf
Verification criteria
Valid Playfair output round-trips to the prepared digraph text; Vigenère, Autokey and monoalphabetic substitution recover normalized plaintext with the correct key.
Deliverables
Submit your matrix, key streams, partner round-trips, frequency observations and reasoning for each challenge; do not submit another student’s answers.
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
# EC02 · Historical ciphers II — Playfair, Vigenère, Autokey and frequency analysis
**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
Encrypt and decrypt paired messages using four classical ciphers and analyze their statistical weaknesses.
**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. Playfair digraphs and peer exchange — complete its numbered steps and record the requested evidence.
3. Monoalphabetic substitution, Vigenère and Autokey — complete its numbered steps and record the requested evidence.
4. Classical ciphertext analysis — complete its numbered steps and record the requested evidence.
5. Python frequency analysis (bonus) — complete its numbered steps and record the requested evidence.
**Evidence:** Valid Playfair output round-trips to the prepared digraph text; Vigenère, Autokey and monoalphabetic substitution recover normalized plaintext with the correct key.
**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. Playfair digraphs and peer exchange — complete its numbered steps and record the requested evidence.
3. Monoalphabetic substitution, Vigenère and Autokey — complete its numbered steps and record the requested evidence.
4. Classical ciphertext analysis — complete its numbered steps and record the requested evidence.
5. Python frequency analysis (bonus) — complete its numbered steps and record the requested evidence.
6. 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
# =====================================================================
# EC02 | Code cell 01 | Historical ciphers II — Playfair, Vigenère, Autokey and frequency analysis
# 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 02 — normalized classical-cipher exercises, not secure encryption."""
from collections import Counter
from string import ascii_uppercase as A
# Define the reusable operation clean; keep its logic separate from the trial.
def clean(text): return ''.join(c for c in text.upper() if c in A)
### Implementation cell 2
Inspect the definitions, then execute to make them available for the investigation.
08Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC02 | Code cell 02 | Historical ciphers II — Playfair, Vigenère, Autokey and frequency analysis
# 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 playfair; keep its logic separate from the trial.
def playfair(message,key,decrypt=False):
alphabet=''.join(dict.fromkeys((clean(key)+A).replace('J','I')))
text=clean(message).replace('J','I'); pairs=[]; i=0
if decrypt:
if len(text)%2: raise ValueError('Ciphertext must be even length')
pairs=[text[i:i+2] for i in range(0,len(text),2)]
else:
while i<len(text):
a=text[i]; i+=1
if i==len(text) or text[i]==a: b='Q' if a=='X' else 'X'
else: b=text[i]; i+=1
pairs.append(a+b)
out=[]; shift=-1 if decrypt else 1
for a,b in pairs:
r,c=divmod(alphabet.index(a),5); rr,cc=divmod(alphabet.index(b),5)
if r==rr: out.extend([alphabet[5*r+(c+shift)%5],alphabet[5*rr+(cc+shift)%5]])
elif c==cc: out.extend([alphabet[5*((r+shift)%5)+c],alphabet[5*((rr+shift)%5)+cc]])
else: out.extend([alphabet[5*r+cc],alphabet[5*rr+c]])
return ''.join(out)
# Define the reusable operation substitution; keep its logic separate from the trial.
def substitution(text,key,decrypt=False):
if len(key)!=26 or set(key)!=set(A): raise ValueError('Key is a permutation of A–Z')
return text.upper().translate(str.maketrans(key,A) if decrypt else str.maketrans(A,key))
# Define the reusable operation vigenere; keep its logic separate from the trial.
def vigenere(text,key,autokey=False,decrypt=False):
text,key=clean(text),clean(key)
if not key: raise ValueError('Empty key')
out=''
for i,c in enumerate(text):
if autokey and i>=len(key): k=(out if decrypt else text)[i-len(key)]
else: k=key[i%len(key)]
out+=A[(A.index(c)+(-1 if decrypt else 1)*A.index(k))%26]
return out
### Implementation cell 3
Inspect the definitions, then execute to make them available for the investigation.
10Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC02 | Code cell 03 | Historical ciphers II — Playfair, Vigenère, Autokey and frequency analysis
# Purpose: Implementation cell 3 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 frequency; keep its logic separate from the trial.
def frequency(text,combine=True):
return Counter(c.upper() if combine else c for c in text if c in A+A.lower())
## 4. Execute reference controls
The program checks selected algorithm outcomes. Record the observed output. These checks do not replace the independent calculation assignment.
12Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC02 | Code cell 04 | Historical ciphers II — Playfair, Vigenère, Autokey and frequency analysis
# 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 p for the next computation or reference condition.
p = 'HELLO'
# Set k for the next computation or reference condition.
k = 'POTATO'
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert playfair(playfair(p, k), k, True) == 'HELXLO'
# Repeat the same operation for each configured input so observations are comparable.
for auto in (False, True):
assert vigenere(vigenere(p, k, auto), k, auto, True) == p
# Prepare key; retain only the scope required for this trial.
key = 'QWERTYUIOPASDFGHJKLZXCVBNM'
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert substitution(substitution(p, key), key, True) == p
print('Classical cipher round trips passed; frequency:', frequency(p))
## 5. Controlled variation
Predict the effect of the parameter changes below. Compare each actual result to your prediction.
14Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC02 | Code cell 05 | Historical ciphers II — Playfair, Vigenère, Autokey and frequency analysis
# 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.
# =====================================================================
print("Compare frequency counts for two classroom messages:",Counter("ATTACKATDAWN"),Counter("THEQUICKBROWNFOX"))
## 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.)
16Instructions · 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. Playfair digraphs and peer exchange — 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.
Where does the Autokey key stream come from during decryption?
What information is lost when spaces are removed?
Submission: Submit your matrix, key streams, partner round-trips, frequency observations and reasoning for each challenge; do not submit another student’s answers.
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