Implement reversible alphabet rotation, compare Caesar implementations, and analyze the limited key space of classical ciphers.
The focus of this experiment is to map letters to residues and distinguish rotation from substitution. Students then calculate encoding and inverse decoding under specified mappings, and compare frequency preservation and historical security limitations. 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
Map letters to residues and distinguish rotation from substitution.
Calculate encoding and inverse decoding under specified mappings.
Compare frequency preservation and historical security limitations.
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 map letters to residues and distinguish rotation from substitution, calculate encoding and inverse decoding under specified mappings, and compare frequency preservation and historical security limitations.
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 preservation and historical security limitations. 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 Historical ciphers II — Playfair, Vigenère, Autokey and frequency analysis.
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 I — Rotation, Caesar and substitution
Implement reversible alphabet rotation, compare Caesar implementations, and analyze the limited key space of classical ciphers.
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: Implement reversible alphabet rotation, compare Caesar implementations, and analyze the limited key space of classical ciphers.
Complete the analytical preparation below before programming. Show the intermediate mathematical calculations.
Rotation and alphabet indexing — complete its numbered steps and record the requested evidence.
Four Caesar implementations — complete its numbered steps and record the requested evidence.
Exhaustive Caesar key search — complete its numbered steps and record the requested evidence.
Reference check: A rotation followed by its inverse recovers the original exactly. Every symbol in a substitution key appears once. Caesar brute force enumerates the entire chosen alphabet.
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. Rotation and alphabet indexing — 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 · EC01 · Historical ciphers I — Rotation, Caesar and substitution
Scientific concept map: Plaintext letters — Alphabet indices; Caesar shift — (x+k) mod 26; Ciphertext — Mapped letters; Inverse shift — (y−k) mod 26; Key search — 26 candidates.
Alphabet as a finite set
Assign each permitted symbol a unique integer from 0 to m−1. With m=28, include lowercase letters, a space and a period. Rotation uses modular wraparound: E(x)=(x+k) mod m; D(y)=(y−k) mod m. The same key and alphabet must be used at both ends.
Equivalent implementations
An index lookup, Python translation table and character-code arithmetic can implement the same mapping. The ASCII approach works directly only for contiguous letters; a custom alphabet needs explicit indexing. Test equality of outputs before comparing runtime.
Key-space experiment
A rotation has m candidate keys. A bijective substitution has m! possible keys, but it preserves single-symbol frequencies. Compare a six-letter permutation space with the 28-symbol space without enumerating the latter. These ciphers are historical teaching mechanisms, not secure IoT encryption.
Prerequisites: None — introductory laboratory.
Algorithm structure and data flow. Use the simulation to inspect the corresponding numerical transformations.
Engineering diagrams
A shift maps each symbol to a new alphabet index.
Scientific foundations and worked examples
Rotation as a permutation
A finite alphabet is an ordered set, not necessarily a contiguous range of character codes. For the 28-symbol laboratory alphabet, a rotation replaces position i by (i+k) mod 28. The inverse rotation is −k. Composition of two rotations adds their shifts modulo the alphabet length. With the six-symbol alphabet abcdef, a left rotation by 2 produces cdefab. A general substitution instead permits any bijection; it has 28! possible mappings if all 28 symbols participate.
Worked Caesar encryption and decryption
For the ordinary 26-letter alphabet with A=0, the word TEST maps to (19,4,18,19). With k=9 the output indices are (2,13,1,2), giving CNBC. Subtracting 9 modulo 26 restores TEST. With an extended alphabet, always use its exact declared ordering. A space or period must be treated as a symbol, not assumed contiguous with ASCII letters.
Four implementations and key recovery
A direct loop finds each symbol index; a translation table precomputes the mapping; ASCII arithmetic works only for contiguous letters; generalized modular indexing works for any ordered alphabet. These are equivalent under identical normalization and alphabet choices. Exhaustive recovery tries each of the m possible shifts including zero. Recognizable language is evidence of a candidate, not proof of a unique plaintext.
Engineering principles · additional worked teaching example
A Caesar cipher maps letters to integers 0–25, adds a key modulo 26, and subtracts it for decryption. With key 5, Z=25 maps to E=4, since 30 mod26=4; subtracting 5 gives −1 mod26=25. Arbitrary substitution needs a bijection. Neither is modern secure encryption.
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
Caesar maps A=0 through Z=25, C=(P+k) mod 26. A shift preserves relative symbol differences and frequency. Example: Z with k=3 gives 2=C; subtract 3 modulo 26 to recover Z.
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 · Alphabet index
Alphabet index
Alphabet index
A=0 … Z=25
Shift
Alphabet index
A=0 … Z=25
Shift
Z (25) + 3 = 28
Reduce
Alphabet index
A=0 … Z=25
Shift
Z (25) + 3 = 28
Reduce
28 mod 26 = 2
Inverse
Alphabet index
A=0 … Z=25
Shift
Z (25) + 3 = 28
Reduce
28 mod 26 = 2
Inverse
C − 3 ≡ Z
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 is Caesar weak?
Only 26 shifts including identity; exhaustive search is trivial.
What does rotation preserve?
Character frequency distribution up to relabeling.
How undo shift k?
Subtract k modulo 26.
Why is substitution not modern encryption?
Language statistics leak structure.
Why does the alphabet contain 28 characters?
It includes 26 letters, a space and a period; arithmetic is modulo 28.
What is rotate("abcdef",2)?
cdefab.
How do you undo a Caesar shift of 5?
Apply a shift of −5 modulo the alphabet length.
What happens after a full alphabet rotation?
The original mapping is restored.
What makes a substitution mapping invertible?
Each source character maps to a distinct destination character.
How many shifts exist for an alphabet of 28 symbols?
28 including the identity shift.
Why is exhaustive search feasible for Caesar?
The key space is only the alphabet size.
How many permutations exist for 4 distinct symbols?
4! = 24.
How does translate differ from a character loop?
It applies a precomputed mapping; both must preserve the same alphabet convention.
What should a round-trip test assert?
decrypt(encrypt(message,key),key) equals the message.
A Caesar alphabet has 26 letters. With A=0, encrypt Z using k=3.
Z has index 25. (25+3) mod 26=2, giving C. Inverse subtraction recovers Z.
A substitution map contains two identical output symbols. Is it a valid reversible permutation?
No. Two input symbols map to the same output, so unique decryption is impossible.
Compare brute force for Caesar and arbitrary 26-letter substitution.
Caesar has 26 shifts including zero. Arbitrary substitution has 26! bijections, although language statistics can greatly reduce practical security.
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 · Alphabet and rotation
For abcdef, rotate by 2 and then reverse the transformation. For the 28-character alphabet abcdefghijklmnopqrstuvwxyz . construct the position-to-symbol mapping for a shift of your choice. Explain the inverse shift.
Engineering method — A Caesar cipher maps letters to integers 0–25, adds a key modulo 26, and subtracts it for decryption. With key 5, Z=25 maps to E=4, since 30 mod26=4; subtracting 5 gives −1 mod26=25. Arbitrary substitution needs a bijection. Neither is modern secure encryption. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
02 · Caesar variants
On paper, encrypt a lowercase word using modular indices, then repeat with a word containing a space and period. Show why the ASCII-only variant needs a separate treatment of these symbols.
Engineering method — A Caesar cipher maps letters to integers 0–25, adds a key modulo 26, and subtracts it for decryption. With key 5, Z=25 maps to E=4, since 30 mod26=4; subtracting 5 gives −1 mod26=25. Arbitrary substitution needs a bijection. Neither is modern secure encryption. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
03 · Exhaustive recovery
Use the two assigned Caesar ciphertexts in the practical activity. Write a candidate-key table, identify plausible decryptions and justify your choice before coding.
Engineering method — A Caesar cipher maps letters to integers 0–25, adds a key modulo 26, and subtracts it for decryption. With key 5, Z=25 maps to E=4, since 30 mod26=4; subtracting 5 gives −1 mod26=25. Arbitrary substitution needs a bijection. Neither is modern secure encryption. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
04 · Permutation and substitution
Calculate the key-space size for alphabets of 4, 6 and 28 distinct symbols. Explain how to invert a permutation and manually decode the first 10 symbols of the assigned substitution ciphertext.
Engineering method — A Caesar cipher maps letters to integers 0–25, adds a key modulo 26, and subtracts it for decryption. With key 5, Z=25 maps to E=4, since 30 mod26=4; subtracting 5 gives −1 mod26=25. Arbitrary substitution needs a bijection. Neither is modern secure encryption. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
05 · Calculation
Calculation · Independent work
Encrypt DOG using Caesar shift 7, then decrypt the result. How many distinct shifts exist including the identity?
Calculation — A Caesar cipher maps letters to integers 0–25, adds a key modulo 26, and subtracts it for decryption. With key 5, Z=25 maps to E=4, since 30 mod26=4; subtracting 5 gives −1 mod26=25. Arbitrary substitution needs a bijection. Neither is modern secure encryption. 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 · EC01-01
Encode W with k=7 and show the reduction.
Intermediate · Calculate or trace
Independent theoretical exercise · EC01-02
Decode B with k=9.
Intermediate · Interpret the result
Independent theoretical exercise · EC01-03
A student computes (25+4)=29 and accesses index 29 of a 26-letter alphabet. Diagnose.
Advanced · Analyze a condition
Independent theoretical exercise · EC01-04
For plaintext ABA, compare ciphertext under shifts 1 and 5. Which property survives?
Advanced · Diagnose or compare
Independent theoretical exercise · EC01-05
There are 26 possible Caesar shifts. What happens when k=26, and how many nonidentity shifts exist?
Challenging · Engineering verification
Independent theoretical exercise · EC01-06
Design a reversible substitution using a supplied alphabet permutation. What must be checked?
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.
Use the 26-letter alphabet to calculate TEST with shift 9 by hand and reverse the result. Explain why ASCII offsets cannot directly represent the 28-symbol alphabet.
Evidence: show the derivation, intermediate values and independent checks; explain any mismatch with the practical result.
Practical laboratory manual
Scientific experimental protocol
Research question: Does alphabet selection affect reversibility and key-space size?
Hold message and alphabet fixed while varying shift; hold shift fixed while comparing alphabets.
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)
Rotation
abcdef, shift +2
cdefab; inverse shift −2 recovers abcdef
Enter observation
Wraparound
28-symbol alphabet, shift 0 and 28
Identical output in both conditions
Enter observation
Substitution
A unique permutation versus a duplicate symbol
Valid key round trips; invalid key is rejected
Enter observation
Analysis: Compare the character loop, translate and arithmetic variants using the same alphabet. Explain why a larger key space alone does not make substitution secure.
Implement reversible alphabet rotation, compare Caesar implementations, and analyze the limited key space of classical ciphers.
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 lab01.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
Rotation and alphabet indexing
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 ALPHABET = "abcdefghijklmnopqrstuvwxyz ."; count its 28 characters and assign indices 0–27.
Implement rotate(characters, shift) using (i+shift) mod len(characters). Run rotate("abcdef",2); compare with cdefab. Repeat for −2, 0 and a full alphabet length.
Open Rotation in Simulation and step through the moved characters; compare your Python trace with the displayed order.
Evidence to record
Record original/rotated alphabets, inverse shift and wraparound.
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
Four Caesar implementations
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.
Implement caesar1(plaintext, characters, shift) with an index-based loop; decrypt using the negative shift.
Implement caesar2 with str.maketrans and str.translate using the rotated alphabet. Compare outputs on identical inputs.
Implement caesar3 using ord/chr for lowercase a–z, then caesar4 using the 28-symbol custom alphabet (space and dot are not contiguous ASCII).
Encrypt the uppercase test word LABS with shifts 3 and 9, then decrypt ODEV and UJKB. Use the 28-symbol alphabet for a separate punctuation test.
Evidence to record
Record all four encrypt/decrypt outputs, and explain why ASCII arithmetic alone does not handle punctuation.
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
Exhaustive Caesar key 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.
Implement bruteForceCaesar(ciphertext, characters) enumerating every shift from 0 to n−1.
Use the first assigned ciphertext below with the 28-symbol alphabet. For the second use lowercase, uppercase, space and dot (54 symbols).
Inspect the candidates and justify the chosen key using readable plaintext, not only the numerical result.
Experimental inputs and checks
Ciphertext A (28 symbols)
x hijquzsbbwdywvquecfbwjwvr
Ciphertext B (54 symbols)
pPzTyNpPfTNXfN TffNRWP TaVXaVNgWPaNpPTFPeNpnFrO
Evidence to record
List candidate count, selected key and recovered message for both provided cases.
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
Permutation and monoalphabetic substitution
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.
Implement permute using random selection without replacement, then slowPermute using itertools.permutations only for a small alphabet. Compare factorial key-space size and elapsed time without enumerating the full alphabet.
Implement monoSub returning both a unique random permutation and ciphertext; implement monoUnSub using the inverse mapping. Test two independently generated keys.
Use the exact provided 28-symbol permutation and ciphertext in the task data below; verify recovery by encrypting the candidate again.
Record key uniqueness, round-trip result and provided challenge recovery.
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
Extended alphabet (lowercase + uppercase + space + period): pPzTyNpPfTNXfN TffNRWP TaVXaVNgWPaNpPTFPeNpnFrO
Substitution key: cpezaojdk lqxhrbvgsft.nwuymi
Ciphertext: erhjgcftqcfkrhsmurtmerxbqafazmfdamokgsfmegubfrjgcbdumqcpi
The provided Caesar strings may contain transcription inconsistencies. Confirm your algorithm with a ciphertext you generate yourself before drawing a conclusion.
Verification criteria
A rotation followed by its inverse recovers the exactly. Every symbol in a substitution key appears once. Caesar brute force enumerates the entire chosen alphabet.
Deliverables
Submit the four implementations, round-trip tests, candidate key table, and an explanation of why classical substitution is insecure.
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
# EC01 · Historical ciphers I — Rotation, Caesar and substitution
**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
Implement reversible alphabet rotation, compare Caesar implementations, and analyze the limited key space of classical ciphers.
**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. Rotation and alphabet indexing — complete its numbered steps and record the requested evidence.
3. Four Caesar implementations — complete its numbered steps and record the requested evidence.
4. Exhaustive Caesar key search — complete its numbered steps and record the requested evidence.
5. Permutation and monoalphabetic substitution — complete its numbered steps and record the requested evidence.
**Evidence:** A rotation followed by its inverse recovers the original exactly. Every symbol in a substitution key appears once. Caesar brute force enumerates the entire chosen alphabet.
**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. Rotation and alphabet indexing — complete its numbered steps and record the requested evidence.
3. Four Caesar implementations — complete its numbered steps and record the requested evidence.
4. Exhaustive Caesar key search — complete its numbered steps and record the requested evidence.
5. Permutation and monoalphabetic substitution — 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
# =====================================================================
# EC01 | Code cell 01 | Historical ciphers I — Rotation, Caesar and substitution
# 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 01 — reversible historical cipher mappings (teaching only)."""
import random
from itertools import permutations
# Set ALPHABET for the next computation or reference condition.
ALPHABET = 'abcdefghijklmnopqrstuvwxyz .'
# Define the reusable operation rotate; keep its logic separate from the trial.
def rotate(characters, shift):
if not characters or len(set(characters)) != len(characters):
raise ValueError('Alphabet must contain distinct symbols')
shift %= len(characters)
return characters[shift:] + characters[:shift]
### Implementation cell 2
Inspect the definitions, then execute to make them available for the investigation.
08Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC01 | Code cell 02 | Historical ciphers I — Rotation, Caesar and substitution
# 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 caesar1; keep its logic separate from the trial.
def caesar1(plaintext, characters, shift):
shifted = rotate(characters, shift)
return ''.join(shifted[characters.index(c)] if c in characters else c for c in plaintext)
# Define the reusable operation caesar2; keep its logic separate from the trial.
def caesar2(plaintext, characters, shift):
return plaintext.translate(str.maketrans(characters, rotate(characters, shift)))
# Define the reusable operation caesar3; keep its logic separate from the trial.
def caesar3(plaintext, shift):
return ''.join(chr(ord('a')+(ord(c)-ord('a')+shift)%26) if 'a' <= c <= 'z' else c for c in plaintext)
### Implementation cell 3
Inspect the definitions, then execute to make them available for the investigation.
10Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC01 | Code cell 03 | Historical ciphers I — Rotation, Caesar and substitution
# 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 caesar4; keep its logic separate from the trial.
def caesar4(plaintext, characters, shift):
return caesar1(plaintext, characters, shift)
# Define the reusable operation bruteForceCaesar; keep its logic separate from the trial.
def bruteForceCaesar(ciphertext, characters):
return [(k, caesar1(ciphertext, characters, -k)) for k in range(len(characters))]
# Define the reusable operation permute; keep its logic separate from the trial.
def permute(characters):
a=list(characters); random.shuffle(a); return ''.join(a)
### Implementation cell 4
Inspect the definitions, then execute to make them available for the investigation.
12Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC01 | Code cell 04 | Historical ciphers I — Rotation, Caesar and substitution
# Purpose: Implementation cell 4 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 slowPermute; keep its logic separate from the trial.
def slowPermute(characters):
if len(characters)>7: raise ValueError('Limit factorial enumeration to ≤7 symbols')
return ''.join(random.choice(list(permutations(characters))))
# Define the reusable operation monoSub; keep its logic separate from the trial.
def monoSub(plaintext, characters):
key=permute(characters)
return key, plaintext.translate(str.maketrans(characters,key))
# Define the reusable operation monoUnSub; keep its logic separate from the trial.
def monoUnSub(ciphertext, characters, key):
if set(key)!=set(characters) or len(key)!=len(characters): raise ValueError('Invalid permutation')
return ciphertext.translate(str.maketrans(key,characters))
## 4. Execute reference controls
The program checks selected algorithm outcomes. Record the observed output. These checks do not replace the independent calculation assignment.
14Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC01 | Code cell 05 | Historical ciphers I — Rotation, Caesar and substitution
# 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 text for the next computation or reference condition.
text = 'hello world.'
# Set cipher for the next computation or reference condition.
cipher = caesar1(text, ALPHABET, 3)
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert rotate('abcdef', 2) == 'cdefab'
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert caesar2(text, ALPHABET, 3) == cipher and caesar4(cipher, ALPHABET, -3) == text
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert caesar3('abcxyz', 3) == 'defabc'
# Prepare (key, c); retain only the scope required for this trial.
key, c = monoSub(text, ALPHABET)
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert monoUnSub(c, ALPHABET, key) == text
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert len(bruteForceCaesar(cipher, ALPHABET)) == 28
print('Caesar output:', cipher, '— all reference checks passed')
## 5. Controlled variation
Predict the effect of the parameter changes below. Compare each actual result to your prediction.
16Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC01 | Code cell 06 | Historical ciphers I — Rotation, Caesar and substitution
# 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 shift in (0,3,7):
c=caesar1("hello world.",ALPHABET,shift)
assert caesar1(c,ALPHABET,-shift)=="hello world."
print(shift,c)
## 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.)
18Instructions · 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. Rotation and alphabet indexing — 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.
How many Caesar keys exist for the 54-symbol alphabet?
Why is frequency analysis effective against a fixed substitution?
Submission: Submit the four implementations, round-trip tests, candidate key table, and an explanation of why classical substitution is insecure.
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