Week 2 Scripting Challenge: Caesarian Cipher
Source: Dev.to
WeekâŻ2 Security Challenge: Caesar Cipher
đĄ Following along? All exercises are openâsource! âď¸ Star the AppSecâExercises repo to track my 48âweek journey from Intel Security to AppSec Engineer.
âWhy would a security engineer need to know a cipher thatâs been broken for 2âŻ000âŻyears?â
Because Grace Nolanâs security interview list explicitly includes Caesar cipher and basic crypto as a common coding challenge. Hereâs why it matters.
Why Caesar Cipher in Security Interviews?
-
Tests StringâManipulation Fundamentals
Security engineers parse logs, analyze malware, and process network data â all requiring strong string skills. The Caesar cipher tests:- Character iteration
- ASCII/Unicode manipulation
- Modular arithmetic
- Case preservation
-
Reveals Cryptography Understanding
Interviewers want to see if you understand:- Encryption vs. Encoding â Caesar is symmetric encryption (requires a key).
- Key Space â Only 26 possible keys â trivially bruteâforceable.
- Frequency Analysis â Statistical attacks on substitution ciphers.
- Why Modern Crypto Exists â Understanding what makes AESâ256 different.
-
Foundation for RealâWorld Security Concepts
- Shift operations â ROT13, XOR operations.
- Symmetric keys â Sharedâsecret cryptography.
- Cryptanalysis â Breaking weak crypto.
- Defense in depth â Why we donât rely on a single encryption method.
The Challenge
Used by Julius Caesar to protect military messages inâŻ58âŻBC, the Caesar cipher shifts each letter by a fixed number of positions in the alphabet.
Example
HELLO + shift(3) = KHOOR
XYZ + shift(3) = ABC (wrapâaround!)
Your task is to implement this transformation while preserving case and handling edge cases.
Your Mission: Build It
PartâŻ1 â Encryption
"""
Exercise 3: Caesar Cipher Encoder/Decoder
Week 2 â Python Strings Practice
Inspired by: Python Workout, Second Edition by Reuven M. Lerner
- ChapterâŻ3 (Strings), pagesâŻ962â1200
- ExerciseâŻ5 (Pig Latin), demonstrating string transformation
Security Context: Grace Nolan's Security Coding Challenges
Reference: Extended 48âWeek Security Engineering Curriculum, WeekâŻ90
"""
def caesar_encrypt(plaintext: str, shift: int) -> str:
"""
Encrypt text using the Caesar cipher.
Args:
plaintext: Text to encrypt.
shift: Number of positions to shift (can be negative or >26).
Returns:
Encrypted ciphertext with original case preserved and
nonâalphabetic characters left untouched.
"""
# Your code here
pass
PartâŻ2 â Decryption
def caesar_decrypt(ciphertext: str, shift: int) -> str:
"""
Decrypt Caesarâcipher text.
Args:
ciphertext: Encrypted text.
shift: Number of positions used in encryption.
Returns:
Decrypted plaintext with original case preserved.
"""
# Your code here
pass
Requirements
- â
Preserve case â
HelloâKhoor(notkhoor). - â
Keep nonâletters â
Hello, World!âKhoor, Zruog!. - â
Handle wrapâaround â
XYZ + 3âABC. - â
Support negative shifts â
shift(-3)= decrypt withshift(3). - â
Work with any shift â including
shift(26),shift(0),shift(100).
Sample Test Cases (10âŻofâŻ95)
# Test 1: Basic encryption
assert caesar_encrypt("HELLO", 3) == "KHOOR"
# Test 2: Wraparound
assert caesar_encrypt("XYZ", 3) == "ABC"
# Test 3: Mixed case preserved
assert caesar_encrypt("Hello, World!", 13) == "Uryyb, Jbeyq!"
# Test 4: Nonâalphabetic preserved
assert caesar_encrypt("test@example.com", 5) == "yjxy@jcfruqj.htr"
# Test 5: Negative shift (decrypt)
assert caesar_encrypt("KHOOR", -3) == "HELLO"
# Test 6: Decryption
assert caesar_decrypt("KHOOR", 3) == "HELLO"
# Test 7: Roundâtrip
assert caesar_decrypt(caesar_encrypt("SECURITY", 7), 7) == "SECURITY"
# Test 8: ROT13 (shiftâŻ13)
assert caesar_encrypt("HELLO", 13) == "URYYB"
# Test 9: ROT13 property (apply twice = original)
assert caesar_encrypt(caesar_encrypt("Python", 13), 13) == "Python"
# Test 10: Large shift (moduloâŻ26)
assert caesar_encrypt("HELLO", 29) == "KHOOR" # 29âŻ%âŻ26 = 3
Security Lessons from the Caesar Cipher
LessonâŻ1 â BruteâForce Is Trivial
def brute_force_caesar(ciphertext: str):
"""Try all 26 possible shifts and print the results."""
for shift in range(26):
plaintext = caesar_decrypt(ciphertext, shift)
print(f"Shift {shift}: {plaintext}")
# Example
brute_force_caesar("KHOOR")
Realâworld parallel: Weak passwords with tiny key spaces (e.g., a 4âdigit PIN = 10âŻ000 possibilities).
LessonâŻ2 â Frequency Analysis Breaks It
def frequency_analysis(ciphertext: str) -> int:
"""
Estimate the shift by assuming the most common letter in English
('E') corresponds to the most common letter in the ciphertext.
"""
freq = {}
for ch in ciphertext.upper():
if ch.isalpha():
freq[ch] = freq.get(ch, 0) + 1
most_common = max(freq, key=freq.get)
likely_shift = (ord(most_common) - ord('E')) % 26
return likely_shift
Realâworld parallel: Sideâchannel attacks, timing attacks, traffic analysis.
LessonâŻ3 â Security Through Obscurity Fails
The Caesar cipher relies on the shift value being secret. Even without knowing the shift, itâs easily broken.
Realâworld parallel:
- Hiding API endpoints doesnât secure them.
- Obfuscating code doesnât prevent reverse engineering.
- âSecurity by obscurityâ is not a defense.
What Makes Modern Crypto Different?
| Feature | Caesar Cipher | AESâ256 |
|---|---|---|
| Key space | 26 possible keys | 2²âľâś possible keys |
| Resistance to bruteâforce | Trivial (seconds) | Practically impossible with current tech |
| Resistance to frequency analysis | None (simple substitution) | Strong (confusion & diffusion) |
| Use case | Educational / toy | Realâworld data protection |
Happy coding, and may your shifts always be correct!
Possible Keys
-
Frequency analysis
-
Resistant to knownâplaintext attacks
-
Same letter â same output
-
CBC/GCM modes prevent patterns
-
Broken in seconds
-
Computationally infeasible to break
Interview FollowâUp Questions
Be prepared to answer:
Q: âHow would you break this cipher without knowing the shift?â
A:
- Bruteâforce all 26 shifts.
- Frequency analysis comparing to English letter frequencies.
Q: âWhatâs the difference between Caesar cipher and XOR cipher?â
A: Both are symmetric, but XOR uses binary operations and can have variableâlength keys.
Q: âWhy do we call ROT13 a special case?â
A: Shift ofâŻ13 is selfâinverse: encrypt(encrypt(x)) = x because 13 + 13 = 26 ⥠0 (modâŻ26).
Q: âHow would you extend this to support Unicode/emoji?â
A: Handle different codeâpoint ranges or use a lookup table instead of modular arithmetic.
RealâWorld Applications (Historical)
1. ROT13 (Still Used Today!)
# Hide spoilers on forums, email, Usenet
rot13 = lambda s: caesar_encrypt(s, 13)
print(rot13("Darth Vader is Luke's father"))
# â "Qnegu Inqre vf Yhxr'f sngure"
2. Simple Obfuscation
# Hide config values (NOT secure, just obscured)
api_key = caesar_encrypt("secret_key_12345", 7)
# Decode when needed
real_key = caesar_decrypt(api_key, 7)
Warning: Never use Caesar for real security!
Python Skills Youâll Practice
From Python Workout â ChapterâŻ3 (pagesâŻ962â1200):
- â
String iteration â
for char in text - â
Character checking â
.isalpha(),.isupper(),.islower() - â
ASCII conversions â
ord(),chr() - â String building â concatenation vs. list joining
- â
Modular arithmetic â
(x + shift) % 26
From Grace Nolanâs Interview Prep:
- â Algorithmic thinking â shift operations
- â Edgeâcase handling â empty strings, special characters
- â Code clarity â clean, readable implementation
- â Testing mindset â comprehensive test coverage
Next Steps: Breaking Crypto
1. Build a Cryptanalysis Tool
def crack_caesar(ciphertext):
"""
Automatically crack Caesar cipher using:
1. Brute force (try all 26 shifts)
2. Frequency analysis
3. Dictionary matching (check if result contains English words)
"""
pass
2. Extend to Vigenère Cipher
Multiâcharacter keys: HELLO with key ABC â HFNLP
- Key repeats: H+A,âŻE+B,âŻL+C,âŻL+A,âŻO+B
- More secure than Caesar (but still breakable!)
3. Compare with Modern Crypto
Implement a simple XOR cipher, then research:
- Why XOR with a random key (oneâtime pad) is theoretically unbreakable.
- Why reusing keys breaks XOR.
- How AES differs from substitution ciphers.
Resources
Cryptography
- âThe Code Bookâ by SimonâŻSingh â excellent history of cryptography.
- âCryptography Engineeringâ by Ferguson, Schneier, Kohno â modern crypto.
- Stanford CryptographyâŻI (Coursera) â DanâŻBonehâs course.
Python String Manipulation
- Python Workout, Second Edition by ReuvenâŻM.âŻLerner â ChapterâŻ3 (pagesâŻ962â1200).
- Effective Python by BrettâŻSlatkin â ItemâŻ11: Slicing sequences.
Security Interview Prep
- Grace Nolanâs Notes (GitHub:
gracenolan/Notes). - âCracking the Coding Interviewâ â securityâfocused problems.
- PortSwigger Web Security Academy â modern crypto vulnerabilities.
Get the Full Exercise
â Star the AppSecâExercises repo on GitHub to get all 95 test cases and follow my securityâengineering journey!
Whatâs in the repo:
exercise_03_caesar_cipher.pyâ complete exercise with 95 test cases.- My solution â full implementation with detailed code.
- Weekly security challenges aligned with my 48âweek curriculum.
- LeetCodeâstyle format perfect for interview prep.
Why star it?
- Track my progress from IntelâŻSecurity â AppSec Engineer.
- Get notified when new exercises drop weekly.
- Contribute your own solutions and test cases.
- Build your portfolio alongside mine.
All exercises are MITâlicensed â use them for your own interview prep!
My Progress: WeekâŻ2 ofâŻ48
- â DNS Fundamentals
- â TLS/SSL Security
- â Python Workout ChaptersâŻ3â4 (Strings, Lists)
- â 8 PortSwigger SQL Injection Labs
- đ Currently: Caesar cipher + cipherâsuite analyzer
- đ Grace Nolanâs coding challenges: 1/10 complete
Goal: Transition to AppSec Engineer by JuneâŻ2026
â Follow my journey on GitHub â new exercises every week!
The Big Picture
Understanding why Caesar cipher is broken teaches you to:
- â Recognize what makes cryptography secure (key space, resistance to attacks).
- â Think like an attacker (frequency analysis, brute force).
- â Appreciate why we donât roll our own crypto (use proven algorithms).
- â Build a foundation for modern cryptography (AES, RSA, elliptic curves).
In WeekâŻ5 weâll tackle real cryptography: AES, RSA, password hashing with bcrypt/Argon2, and the mistakes that lead to vulnerabilities.
For now, master the fundamentals by building something broken â then learn why itâs broken.
đ Take Action
- â Star AppSecâExercises on GitHub â get weekly security coding challenges.
- đŹ Drop a comment â have you seen Caesar cipher in interviews? What other âbrokenâ security concepts appear?
- đ Follow me on Dev.to and GitHub for my full 48âweek journey.
Currently seeking: Remote Security Engineering roles
Tags
Python #Security #Cryptography #Interview #CyberSecurity #AppSec