What is the Affine Cipher?
The Affine cipher is a monoalphabetic substitution that generalizes Caesar.
Each letter of the alphabet (mapped to an index 0..25) is transformed by a linear function
mod 26 with two parameters: a (slope) and b (shift).
Conceptually: map letters → numbers, apply the affine transform, then map numbers → letters.
If a and 26 are not coprime, the function is not invertible and you cannot decrypt.
Formulas
Encryption: C = (a·P + b) mod 26
Decryption: P = a⁻¹·(C - b) mod 26
Condition: a must be coprime with 26 (gcd(a,26)=1) so that a⁻¹ exists.
Valid a: {1,3,5,7,9,11,15,17,19,21,23,25} ; b ∈ {0..25}
Here a⁻¹ is the modular inverse of a in ℤ26, i.e., a·a⁻¹ ≡ 1 (mod 26).
How it works
1) Choose a coprime with 26 and a b in 0–25.
2) Normalize the text (accents → base). You may choose to preserve ñ/Ñ without encryption for compatibility—just document it.
3) Convert each letter to its index (A=0, …, Z=25), apply C = (a·P + b) mod 26, then map back to letters.
For decryption, compute a⁻¹ (via the extended Euclidean algorithm) and use P = a⁻¹·(C - b) mod 26.
Example
Quick example
Parameters: a=5, b=8 ⇒ E(x) = (5x + 8) mod 26
Plaintext: ATAQUE → indices A=0, T=19, A=0, Q=16, U=20, E=4
Computation:
A: (5·0+8)=8 → I | T: (5·19+8)=103≡25 → Z |
A: 8 → I | Q: 88≡10 → K |
U: 108≡4 → E | E: 28≡2 → C
Ciphertext: IZIKEC
For decryption with a=5, the inverse is a⁻¹=21 (since 5·21=105≡1 mod 26).
History
- Formalizes and generalizes classical substitutions (like Caesar) using modular algebra.
- Widely used in teaching to introduce modular inverses and linear functions over ℤn.
Classic attacks
- Frequency + known pairs: two plaintext/ciphertext pairs
(P₁,C₁),(P₂,C₂)solve foraandb. - Brute force: the key space is small (12 valid
a× 26 values ofb= 312 combinations). - Language cues: guessing likely mappings (e.g., plaintext
Eto a frequent ciphertext letter) speeds up recovery.
It is still monoalphabetic: overall letter frequencies are preserved, which is why it’s vulnerable.
Pros and cons
Pros
- Generalizes Caesar; ideal for teaching modular arithmetic and inverses.
- Flexible parameters (
a,b) and simple implementation. - Great for interactive tools and classroom exercises.
Cons
- Monoalphabetic: vulnerable to frequency analysis and to brute force (312-key space).
- If
ais not coprime with 26, no inverse exists and decryption is impossible. - Provides no integrity or authenticity; it only hides letters via a linear function.
Affine Encryption & Decryption Tool
Allowed values for a: 1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25.
b accepts negatives and large values; normalized mod 26 (e.g., 27→1, −1→25).