Affine Cipher
Linear Substitution Cipher Calculator
Affine Cipher Calculator & Guide
1. The Mathematical Engine: Linear Congruence
The Affine Cipher is a type of Monoalphabetic Substitution Cipher. It maps each letter of the alphabet to a numeric value ($A=0, B=1, \dots, Z=25$) and transforms it using a linear equation.
The Encryption Formula
- $x$: The numeric value of the plaintext letter.
- $a$: The multiplicative key (Slope). Must be coprime to 26.
- $b$: The additive key (Intercept). Any integer 0-25.
- $m$: The size of the alphabet (26).
The Decryption Formula
Decryption is harder. You cannot simply divide. In modular arithmetic, we multiply by the Modular Multiplicative Inverse ($a^{-1}$).
2. The "Coprime" Trap: Why Key A Matters
Many students ask: "Why can't I use 4 as Key A?"
For the cipher to be reversible (i.e., for decryption to work), the function must be a Bijection (one-to-one mapping). This only happens if $gcd(a, 26) = 1$.
Since $26 = 2 \times 13$, any even number (2, 4, 6...) or multiple of 13 is forbidden.
3. Manual Calculation Example
Let's encrypt the letter "H" using Key $a=5, b=8$.
Step 1: Convert to Number
"H" is the 8th letter, but since we start at 0 (A=0), $x = 7$.
Step 2: Apply Formula
Step 3: Convert Back
Number 17 corresponds to the letter "R". So, H becomes R.
Step 4: Verification (Decryption)
To decrypt, we first find $a^{-1}$ where $5 \times a^{-1} \equiv 1 \pmod{26}$.
The inverse of 5 is 21 (since $5 \times 21 = 105 = 4 \times 26 + 1$).
4. Cracking the Code: Brute Force & Frequency Analysis
Is the Affine Cipher secure? Absolutely not. It is vulnerable to two major attacks.
A. Brute Force Attack
The key space is incredibly small.
Possible values for $a$: 12
Possible values for $b$: 26
Total Keys: $12 \times 26 = 312$.
A human can check 312 keys in an hour; a computer does it in microseconds.
B. Frequency Analysis
Since it is a monoalphabetic substitution, the frequency of letters is preserved.
If the most common letter in the ciphertext is 'X', and we know 'E' is the most common letter in English, we can assume:
$E(x_E) = x_X$
We can build a system of linear equations to solve for $a$ and $b$ instantly.
5. Developer's Corner: Python Implementation
Want to build your own solver? Here is the core logic for the Modular Inverse in Python 3.
# Extended Euclidean Algorithm
for x in range(1, m):
if ((a % m) * (x % m)) % m == 1:
return x
return -1
# Example usage for decryption
key_a = 5
key_b = 8
inv_a = mod_inverse(key_a, 26) # Returns 21
6. Professor's FAQ Corner
References
- Stinson, D. R. (2005). Cryptography: Theory and Practice. CRC Press.
- Singh, S. (1999). The Code Book: The Science of Secrecy. Fourth Estate.
- Rosen, K. H. (2011). Elementary Number Theory and Its Applications. Pearson.