Affine Cipher
A mathematical substitution cipher defined by two numbers a and b (mod 26).
History & context
The affine cipher generalizes Caesar by adding a multiplication step. Instead of shifting letters by a fixed amount, it multiplies the letter index by a and then adds b, all modulo 26. This creates a larger keyspace than Caesar, but it remains monoalphabetic substitution, so classical frequency analysis still breaks it quickly.
How Affine Cipher works
Convert letters to numbers A=0..Z=25. Choose parameters a and b. Compute ciphertext index as (a*x + b) mod 26. To decode, compute x = a^{-1} * (y - b) mod 26, where a^{-1} is the modular inverse of a modulo 26.
Core rules
- a must be coprime with 26 (otherwise no inverse exists and decoding is impossible).
- Valid a values mod 26 are: 1,3,5,7,9,11,15,17,19,21,23,25.
- b can be any integer 0–25.
- Still monoalphabetic: one plaintext letter always maps to the same ciphertext letter for a given key.
Worked example
How to encode / decode
Step-by-step
- Choose a and b (a must be coprime with 26).
- Map letters A=0..Z=25.
- Compute (a*x + b) mod 26 for each letter.
- Map result back to letters.
How to break a Affine Cipher
Affine is still a monoalphabetic substitution, so it is breakable via frequency analysis. Additionally, the keyspace is small enough to brute force: there are 12 valid a values and 26 b values, so only 312 possible keys.
Practical checklist
- Brute force all valid (a,b) pairs (312 keys).
- Score outputs using English-likeness (dictionary hits, common words).
- Frequency analysis shortcut: map the most common ciphertext letter to E (and second-most to T) to solve for a and b.
- If you have a known plaintext fragment (crib), solve directly using two letter mappings.
What frequency looks like
Affine preserves frequency distribution like Caesar because it is still monoalphabetic substitution. So ciphertext has strong peaks and IoC close to English. The difference is that the substitution is not a simple shift; it’s a permutation defined by the linear function.
- IoC is close to English (~0.066).
- Single-letter frequencies remain strongly peaked.
- Brute force reveals readable output very quickly because the keyspace is tiny.
Common mistakes
- Using an invalid a (no modular inverse).
- Mixing up encode vs decode formula.
- Forgetting mod 26 wrap-around.
- Inconsistent handling of punctuation/case.
Variants
- Affine over different alphabets (e.g., including digits).
- Affine on ASCII ranges (rare).
- Multi-alphabet affine (becomes polyalphabetic, not standard).
Practice
Try brute forcing Affine keys and compare scoring methods (word hits vs bigram scoring).
Try these prompts
- Encode HELLOWORLD with a=7, b=3.
- Given ciphertext and knowing it’s Affine, brute force all 312 keys and pick the best output.
- Try solving for a and b using assumptions about most common letters.