The Affine cipher turns each letter into a number, passes it through a simple algebraic formula, and turns the result back into a letter.
Most beginner ciphers feel like alphabet games. Caesar shifts the alphabet. Atbash reverses it. A1Z26 replaces letters with their positions. They are clear, useful, and memorable, but they still feel close to the surface of writing.
The Affine cipher goes one step deeper.
It says: do not just move the alphabet by hand. Treat the alphabet as arithmetic.
A becomes 0. B becomes 1. C becomes 2. The cipher then takes each number, multiplies it, adds another number, wraps the result around the alphabet, and turns it back into a letter. What looks like a secret alphabet is really the output of a formula.
That formula is usually written:
$$ E(x) = (ax + b) \bmod 26 $$
It is not a modern secure encryption system. It is far too small, too regular, and too easy to break. But as a teaching cipher, it is excellent. It introduces modular arithmetic, key validity, inverse operations, and the idea that encryption and decryption can be described as mathematical functions.
That is the real value of the Affine cipher.
It is not the cipher that made classical cryptography secure. It is the cipher that makes classical cryptography start to look mathematical.
Affine Cipher at a Glance
| Feature | Affine Cipher |
|---|---|
| Type | Monoalphabetic substitution cipher |
| Main idea | Encrypt each letter with a linear modular formula |
| Standard formula | $E(x) = (ax + b) \bmod 26$ |
| Usual alphabet numbering | A = 0, B = 1, C = 2, ..., Z = 25 |
| Key | Two numbers: a and b |
| Key rule | a must be coprime with 26 |
| Common example key | a = 5, b = 8 |
| Example | AFFINE -> IHHWVC |
| Decryption | Uses the modular inverse of a |
| Security | Educational only; weak by modern standards |
| Best use | Learning substitution, modular arithmetic, inverses, and classical codebreaking |
The Affine cipher is often taught after Caesar and Atbash because it shows how those simpler ciphers fit inside a larger mathematical pattern. A Caesar shift is just an Affine cipher where the multiplication part is 1. Atbash can also be written as a special Affine transformation.
That makes Affine a useful bridge. It connects simple alphabet substitution to the more mathematical world of later cryptography.
The Alphabet Becomes a Number Line
The Affine cipher begins by doing something simple but important: it numbers the alphabet.
The usual convention is:
| Letter | A | B | C | D | E | F | G | H | I | J | K | L | M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Number | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
| Letter | N | O | P | Q | R | S | T | U | V | W | X | Y | Z |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Number | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 |
Once the alphabet has been turned into numbers, the cipher applies a formula.
For encryption, the standard formula is:
$$ E(x) = (ax + b) \bmod 26 $$
Here is what each part means:
| Symbol | Meaning |
|---|---|
x |
The plaintext letter number |
a |
The multiplication part of the key |
b |
The shift part of the key |
mod 26 |
Wrap the result around the 26-letter alphabet |
A common teaching key is:
a = 5
b = 8
So the formula becomes:
$$ E(x) = (5x + 8) \bmod 26 $$
Take the letter A.
A = 0
E(0) = (5 x 0 + 8) mod 26 = 8
8 = I
So:
A -> I
Take the letter B.
B = 1
E(1) = (5 x 1 + 8) mod 26 = 13
13 = N
So:
B -> N
Take the letter C.
C = 2
E(2) = (5 x 2 + 8) mod 26 = 18
18 = S
So:
C -> S
Already the cipher is doing something more interesting than a Caesar shift. The alphabet is not merely sliding forward. It is being rearranged by arithmetic.
With a = 5, b = 8, the full substitution alphabet is:
| Plain alphabet | A | B | C | D | E | F | G | H | I | J | K | L | M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Cipher alphabet | I | N | S | X | C | H | M | R | W | B | G | L | Q |
| Plain alphabet | N | O | P | Q | R | S | T | U | V | W | X | Y | Z |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Cipher alphabet | V | A | F | K | P | U | Z | E | J | O | T | Y | D |
That table looks like a scrambled alphabet.
But it is not random.
It is the visible trace of the formula.
Two Numbers, One Trap
The Affine cipher key has two parts:
a, the multiplierb, the shift
The b value is easy to understand. It behaves like a shift. In the standard English alphabet, b is usually chosen from 0 to 25.
The a value is more interesting. It controls the multiplication, but not every number works.
For the ordinary 26-letter alphabet, a must be coprime with 26. That means a and 26 must have no shared factor except 1.
The valid values of a are:
1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25
The value b can be:
0 through 25
So the standard English Affine cipher has:
12 x 26 = 312 valid keys
This is larger than Caesar's 26 possible shifts, but still tiny. A computer can try every Affine key almost instantly.
The rule about a is not mathematical decoration. It is essential.
If a is badly chosen, the cipher stops being reversible.
When a Bad Key Destroys the Cipher
A cipher must be reversible. If two different plaintext letters encrypt to the same ciphertext letter, decryption becomes ambiguous. The receiver cannot reliably recover the original message.
That is why the value of a matters.
Try a bad key:
a = 2
b = 1
The formula becomes:
$$ E(x) = (2x + 1) \bmod 26 $$
Now encrypt A.
A = 0
E(0) = (2 x 0 + 1) mod 26 = 1
1 = B
So:
A -> B
Now encrypt N.
N = 13
E(13) = (2 x 13 + 1) mod 26
E(13) = 27 mod 26
27 mod 26 = 1
1 = B
So:
N -> B
That is a failure.
A and N both encrypt to B.
If a receiver later sees the ciphertext letter B, should it decrypt to A or N?
There is no way to know.
The problem is that 2 and 26 share a factor. Multiplication by 2 does not shuffle the alphabet cleanly. It causes collisions.
A valid value of a must make multiplication act like a clean rearrangement of the alphabet, not a many-to-one collapse. Every plaintext letter needs exactly one ciphertext partner, and every ciphertext letter needs exactly one plaintext partner.
This is one of the Affine cipher's best lessons.
Encryption is not merely changing symbols.
Encryption must change symbols in a way that the right person can undo.
A Worked Example: AFFINE Becomes IHHWVC
Let us use the standard teaching key:
a = 5
b = 8
So the encryption formula is:
$$ E(x) = (5x + 8) \bmod 26 $$
Now encrypt:
AFFINE
First convert the letters into numbers.
| Letter | A | F | F | I | N | E |
|---|---|---|---|---|---|---|
| Number | 0 | 5 | 5 | 8 | 13 | 4 |
Now apply the formula to each number.
| Plain letter | Number | Calculation | Result | Cipher letter |
|---|---|---|---|---|
| A | 0 | 5 x 0 + 8 |
8 | I |
| F | 5 | 5 x 5 + 8 = 33; 33 mod 26 |
7 | H |
| F | 5 | 5 x 5 + 8 = 33; 33 mod 26 |
7 | H |
| I | 8 | 5 x 8 + 8 = 48; 48 mod 26 |
22 | W |
| N | 13 | 5 x 13 + 8 = 73; 73 mod 26 |
21 | V |
| E | 4 | 5 x 4 + 8 = 28; 28 mod 26 |
2 | C |
Put the letters together:
| Plaintext | A | F | F | I | N | E |
|---|---|---|---|---|---|---|
| Ciphertext | I | H | H | W | V | C |
So:
AFFINE -> IHHWVC
This classic Affine cipher example shows two things at once.
First, the encryption is fully mechanical. There is no guessing or improvising. Every letter goes through the same formula.
Second, repeated letters remain repeated. The two Fs in AFFINE become two Hs in IHHWVC.
That repeated-letter pattern is useful for the receiver.
It is also useful for an attacker.
The Clock Arithmetic of Secret Alphabets
The phrase mod 26 is what keeps the cipher inside the alphabet.
If a calculation gives 8, that is easy: 8 means I.
But if a calculation gives 33, there is no 33rd letter in the ordinary English alphabet. So the result wraps around.
33 mod 26 = 7
7 = H
This is modular arithmetic. It is the same basic idea as clock arithmetic.
On a 12-hour clock, if it is 10 o'clock and you add 5 hours, you do not say 15 o'clock. You wrap around and say 3 o'clock.
In modular arithmetic, only the remainder matters. On a 12-hour clock, 15 and 3 land in the same place.
The Affine cipher does the same thing, except the "clock" has 26 positions instead of 12.
The alphabet is the clock face.
A is 0
B is 1
C is 2
...
Z is 25
After Z, the count wraps back around.
This is why the Affine cipher is such a clean step beyond Caesar. It does not simply say "move letters forward." It says "work inside a finite number system."
That idea becomes important later. Modern cryptography uses vastly more sophisticated mathematics, but the habit of treating messages as elements inside a mathematical space is already visible here in miniature.
Decryption Is Not Division: It Is an Inverse
Encryption uses:
$$ E(x) = (ax + b) \bmod 26 $$
To decrypt, the receiver must reverse the process.
In ordinary algebra, if:
y = 5x + 8
then you would subtract 8 and divide by 5.
But modular arithmetic does not use ordinary division in quite that way. In modular arithmetic, "division" only works when the number you want to divide by has a modular inverse.
That is why the Affine cipher uses the modular inverse of a.
The decryption formula is:
$$ D(y) = a^{-1}(y - b) \bmod 26 $$
Or, written with extra grouping:
$$ D(y) = (a^{-1} \times (y - b)) \bmod 26 $$
Here is what each part means:
| Symbol | Meaning |
|---|---|
y |
The ciphertext letter number |
b |
The shift part of the key |
a^-1 |
The modular inverse of a |
mod 26 |
Wrap the result around the alphabet |
The modular inverse of a is the number that undoes multiplication by a modulo 26.
For our example:
a = 5
We need a number that makes this true:
$$ 5 \times a^{-1} \equiv 1 \pmod{26} $$
That number is 21.
Why?
5 x 21 = 105
105 mod 26 = 1
So:
$$ 5^{-1} \bmod 26 = 21 $$
The decryption formula for the key a = 5, b = 8 is therefore:
$$ D(y) = 21(y - 8) \bmod 26 $$
That looks more intimidating than encryption, but the logic is simple.
Encryption says:
- multiply by
5 - add
8 - wrap around
26
Decryption says:
- subtract
8 - multiply by the inverse of
5 - wrap around
26
The second process undoes the first.
That is the algebraic heart of the cipher.
Decrypting a Message by Reversing the Formula
Now decrypt:
QCCZ IZ XIOV
using the key:
a = 5
b = 8
We already know that the inverse of 5 modulo 26 is 21, so:
$$ D(y) = 21(y - 8) \bmod 26 $$
Start with Q.
Q = 16
D(16) = 21(16 - 8) mod 26
D(16) = 21 x 8 mod 26
21 x 8 = 168
168 mod 26 = 12
12 = M
So:
Q -> M
Now try C.
C = 2
D(2) = 21(2 - 8) mod 26
21 x -6 = -126
-126 mod 26 = 4
4 = E
So:
C -> E
The first three letters therefore give MEE, and the final Z completes the word as MEET.
Continue the same process and the full phrase becomes:
| Ciphertext | Q | C | C | Z | I | Z | X | I | O | V | ||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Plaintext | M | E | E | T | A | T | D | A | W | N |
So:
QCCZ IZ XIOV -> MEET AT DAWN
This is where Affine is satisfying. The same neat formula that created the ciphertext also gives you a precise way to undo it. The cipher is not just a table. It is a reversible mathematical operation.
But that neatness cuts both ways.
The same structure that helps the intended receiver can also help an attacker.
Caesar, ROT13, and Atbash Inside One Formula
One reason the Affine cipher is worth learning is that it gathers several simpler ciphers under one mathematical roof.
The Caesar cipher uses a shift:
$$ E(x) = (x + b) \bmod 26 $$
That is just the Affine cipher with:
a = 1
So every Caesar cipher is an Affine cipher.
ROT13 is also a Caesar cipher, so it is an Affine cipher too:
$$ E(x) = (x + 13) \bmod 26 $$
That means ROT13 is Affine with:
a = 1
b = 13
Atbash also fits the Affine pattern. Atbash reverses the alphabet:
A -> Z
B -> Y
C -> X
In 0-25 numbering, that reversal can be written as:
$$ E(x) = 25 - x $$
In Affine form, that becomes:
$$ E(x) = (25x + 25) \bmod 26 $$
So Atbash is also a special Affine cipher.
| Cipher | Affine form |
|---|---|
| Caesar shift | $E(x) = (x + b) \bmod 26$ |
| ROT13 | $E(x) = (x + 13) \bmod 26$ |
| Atbash | $E(x) = (25x + 25) \bmod 26$ |
| General Affine cipher | $E(x) = (ax + b) \bmod 26$ |
That makes the Affine cipher conceptually useful. Caesar, ROT13, and Atbash are not isolated tricks. They can all be described as simple modular transformations.
Affine also points forward.
A general monoalphabetic substitution allows any scrambled alphabet, not just one generated by a formula. Vigenere changes the substitution as the message progresses, so the same plaintext letter can encrypt differently depending on its position and keyword. The Hill cipher takes the mathematical instinct further by encrypting blocks of letters with matrix multiplication modulo 26.
In that sequence, Affine sits exactly where it should.
After alphabet tricks.
Before heavier mathematics.
A Cipher with No Great Legend
Some classical ciphers come with dramatic historical stories.
The Caesar cipher is associated with Julius Caesar.
The Vigenere cipher belongs to the long history of polyalphabetic substitution.
The Playfair cipher is tied to nineteenth-century British diplomatic and military use.
The Hill cipher has a named inventor, Lester S. Hill, and a clear twentieth-century mathematical identity.
The Affine cipher does not have the same kind of famous origin story.
It is better understood as a mathematical generalisation of substitution ciphers rather than a historically dramatic battlefield system. It appears frequently in cryptography teaching because it is compact, exact, and mathematically revealing.
That modesty is worth preserving.
The Affine cipher should not be presented as a world-changing military cipher. Its historical significance is not that it transformed diplomacy or warfare. Its importance is educational and structural.
It shows how classical substitution can be generated by a formula.
That is enough.
Not every cipher needs a legend to matter.
Why This Cipher Was Useful Anyway
The Affine cipher is weak, but weak does not mean useless.
For short messages, puzzles, classroom demonstrations, and hand-worked examples, it has several genuine strengths.
It is compact. The whole cipher can be described with two numbers and one formula.
It is more flexible than Caesar. Instead of 26 possible shifts, standard English Affine has 312 valid keys.
It produces substitution alphabets that look less obvious than simple Caesar shifts.
It teaches reversibility. The rule that a must be coprime with 26 is a clear demonstration that not every transformation can be safely undone.
It introduces modular inverses. That is a genuinely important mathematical idea, and the Affine cipher gives it a practical reason to exist.
It also teaches a useful programming pattern:
- turn characters into numbers
- transform the numbers
- turn them back into characters
- preserve punctuation if needed
- validate keys
- handle errors
That same general rhythm appears again and again in coding work, even outside cryptography.
So the Affine cipher is useful in exactly the right educational sense. It is small enough to hold in your head, but rich enough to teach something real.
The Pattern Still Leaks Through
The Affine cipher looks mathematical, but it remains a monoalphabetic substitution cipher.
That means each plaintext letter always encrypts to the same ciphertext letter.
With a = 5, b = 8:
E -> C
T -> Z
A -> I
So every E becomes C, every T becomes Z, and every A becomes I.
This fixed mapping is the cipher's central weakness.
In English, letters are not evenly distributed. E, T, A, O, I, N, S, H, and R tend to appear often, though the exact order varies by text. A monoalphabetic substitution does not erase that pattern. It only relabels it.
This matters.
If a long plaintext has many Es, the ciphertext will have many copies of whatever E encrypts to.
Using the key a = 5, b = 8:
E = 4
E(4) = (5 x 4 + 8) mod 26
E(4) = 28 mod 26 = 2
2 = C
So E becomes C.
In a long ciphertext made with this key, C may be unusually common.
That gives an attacker a clue.
The Affine cipher changes the labels.
It does not hide the underlying habits of the language.
A Small Keyspace Makes Brute Force Easy
The Affine cipher has 312 valid keys in the standard English alphabet.
That is tiny.
A human might find 312 possibilities tedious. A computer does not care. A short script can try every valid pair of a and b, decrypt the ciphertext, and check which outputs look like English.
That means the Affine cipher has two major weaknesses at once:
| Weakness | Why it matters |
|---|---|
| Monoalphabetic structure | Letter frequencies and repeated patterns survive |
| Small keyspace | Every valid key can be tested quickly |
Compare that with a completely general monoalphabetic substitution cipher.
A general substitution can use any rearrangement of the 26-letter alphabet. That gives:
26!
possible substitution alphabets.
That is:
403,291,461,126,605,635,584,000,000
possible alphabets.
The Affine cipher's 312 keys are only a tiny fraction of all possible substitution alphabets.
But even a huge substitution keyspace does not make monoalphabetic substitution safe against frequency analysis. Affine is worse because it has both the substitution weakness and the tiny keyspace.
It is elegant.
It is not secure.
Breaking Affine with Two Good Guesses
The Affine cipher can often be attacked with algebra.
Suppose an attacker suspects two plaintext/ciphertext pairs.
For example, imagine they guess:
E -> C
T -> Z
Using A = 0 numbering:
| Letter | Number |
|---|---|
| E | 4 |
| C | 2 |
| T | 19 |
| Z | 25 |
The Affine formula is:
$$ y = (ax + b) \bmod 26 $$
So the two guesses give two equations:
$$ 4a + b \equiv 2 \pmod{26} $$
and:
$$ 19a + b \equiv 25 \pmod{26} $$
Now subtract the first equation from the second:
$$ 15a \equiv 23 \pmod{26} $$
To solve this, we need the inverse of 15 modulo 26.
15 and 26 are coprime, and:
15 x 7 = 105
105 mod 26 = 1
So:
$$ 15^{-1} = 7 \pmod{26} $$
Multiply both sides by 7:
a = 23 x 7 mod 26
23 x 7 = 161
161 mod 26 = 5
So:
a = 5
Now substitute that back into:
$$ 4a + b \equiv 2 \pmod{26} $$
That gives:
4 x 5 + b = 2 mod 26
20 + b = 2 mod 26
b = 2 - 20 mod 26
b = -18 mod 26
b = 8
The key is:
a = 5
b = 8
Once the attacker has those two numbers, the whole message can be decrypted.
This is the uncomfortable side of mathematical elegance. The formula that makes the cipher clean also gives the attacker something clean to solve.
A random substitution alphabet has to be reconstructed through patterns, frequencies, and guesses.
An Affine cipher can sometimes be reduced to a pair of modular equations.
Recognising the Affine Cipher in Practice
Affine ciphertext can look like ordinary substitution ciphertext.
For example, using a = 5, b = 8:
THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
becomes:
ZRC KEWSG NPAOV HAT BEQFU AJCP ZRC LIDY XAM
At a glance, that looks reasonably cryptic.
But the structure is still visible.
The word THE appears twice in the plaintext.
The word ZRC appears twice in the ciphertext.
The phrase still has the same number of words.
The word lengths are unchanged.
Repeated letters remain repeated.
Common patterns survive.
A practical codebreaker might proceed like this:
- Check whether the message looks like simple substitution.
- Look for repeated words and repeated letter patterns.
- Try Caesar and Atbash first, because they are common special cases.
- Try all valid Affine keys.
- If those fail, move on to general substitution, Vigenere, or other cipher families.
The Affine cipher does not hide very deeply.
It mostly hides from people who have not yet learned what to test.
Where Affine Appears Today
The Affine cipher does not have the pop-culture footprint of Caesar, Morse code, Atbash, binary, or A1Z26.
You are much more likely to see those simpler systems in television puzzles, escape-room clues, children's code sheets, ARGs, geocaching hints, and visible background riddles. The Affine cipher is less visually immediate. It needs key numbers and modular arithmetic, so it does not work quite as well as a quick on-screen puzzle.
That does not make it obscure.
It appears frequently in:
- introductory cryptography courses
- modular arithmetic exercises
- online cipher tools
- programming tutorials
- recreational cryptography
- puzzle hunts
- codebreaking practice
- educational software exercises
That is exactly its modern role.
Not a serious secure cipher.
Not a famous cinematic code.
But a very good training ground.
A Simple Python Affine Cipher
The Affine cipher is a good programming example because the code follows the mathematics closely.
The script below can:
- encrypt text with an Affine cipher
- decrypt it with the same key
- preserve spaces and punctuation
- preserve uppercase and lowercase letters
- reject invalid values of
a
Python exampleShow code
import math
def mod_inverse(a, m):
"""
Return the modular inverse of a modulo m.
The modular inverse is a number x such that:
(a * x) % m == 1
For example, the inverse of 5 modulo 26 is 21 because:
5 * 21 = 105
105 % 26 = 1
"""
for x in range(m):
if (a * x) % m == 1:
return x
raise ValueError(f"No modular inverse exists for a={a} modulo {m}.")
def check_affine_key(a):
"""
Check that the multiplicative key 'a' is valid.
For the standard 26-letter English alphabet, 'a' must be
coprime with 26. In other words:
gcd(a, 26) must equal 1
If this is not true, the cipher will not decrypt reliably.
"""
if math.gcd(a, 26) != 1:
raise ValueError(
"Invalid Affine key. The value of 'a' must be coprime with 26. "
"Valid values are 1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, and 25."
)
def affine_encrypt(text, a, b):
"""
Encrypt text using the Affine cipher.
Encryption formula:
E(x) = (a*x + b) mod 26
where:
x is the plaintext letter number
a is the multiplication key
b is the shift key
"""
check_affine_key(a)
result = []
for char in text:
if 'A' <= char <= 'Z':
x = ord(char) - ord('A')
y = (a * x + b) % 26
result.append(chr(y + ord('A')))
elif 'a' <= char <= 'z':
x = ord(char) - ord('a')
y = (a * x + b) % 26
result.append(chr(y + ord('a')))
else:
result.append(char)
return ''.join(result)
def affine_decrypt(text, a, b):
"""
Decrypt text using the Affine cipher.
Decryption formula:
D(y) = a_inverse * (y - b) mod 26
where:
y is the ciphertext letter number
a_inverse is the modular inverse of a
"""
check_affine_key(a)
a_inverse = mod_inverse(a, 26)
result = []
for char in text:
if 'A' <= char <= 'Z':
y = ord(char) - ord('A')
x = (a_inverse * (y - b)) % 26
result.append(chr(x + ord('A')))
elif 'a' <= char <= 'z':
y = ord(char) - ord('a')
x = (a_inverse * (y - b)) % 26
result.append(chr(x + ord('a')))
else:
result.append(char)
return ''.join(result)
message = "Meet at dawn!"
a = 5
b = 8
encrypted = affine_encrypt(message, a, b)
decrypted = affine_decrypt(encrypted, a, b)
print("Plaintext :", message)
print("Encrypted :", encrypted)
print("Decrypted :", decrypted)
Expected output:
Plaintext : Meet at dawn!
Encrypted : Qccz iz xiov!
Decrypted : Meet at dawn!
Reading the Code Like the Cipher
The code follows the same rhythm as the mathematics.
First, check_affine_key(a) makes sure the value of a is valid. If a is not coprime with 26, the function stops before producing misleading output.
That is important. A good cipher tool should not quietly accept impossible keys.
Then each letter is converted into a number.
For uppercase letters:
x = ord(char) - ord('A')
So:
| Letter | Number |
|---|---|
| A | 0 |
| B | 1 |
| C | 2 |
The encryption formula is then applied:
y = (a * x + b) % 26
That is exactly:
$$ E(x) = (ax + b) \bmod 26 $$
The result is converted back into a letter:
chr(y + ord('A'))
Lowercase letters are handled the same way using ord('a').
Spaces, punctuation, digits, and symbols are left unchanged. That makes the tool friendlier to use, though it also preserves word shape and punctuation patterns. From a security perspective, that leaks structure. From an educational-tool perspective, it is usually what users expect.
Decryption works by finding the modular inverse of a:
a_inverse = mod_inverse(a, 26)
Then it applies:
x = (a_inverse * (y - b)) % 26
That is the decryption formula:
$$ D(y) = a^{-1}(y - b) \bmod 26 $$
The code is not trying to be clever. It is trying to make the cipher visible.
That is the right priority for an educational cryptography tool.
In modern Python, the modular inverse can also be found with:
pow(a, -1, 26)
But the loop in this example is deliberately easy to inspect. It shows the idea directly: try numbers until one of them undoes the multiplication.
Common Questions About the Affine Cipher
Is the Affine cipher secure?
No. The Affine cipher is a classical educational cipher, not a secure encryption method.
It has only 312 valid keys in the standard English alphabet, and it preserves monoalphabetic frequency patterns. That means repeated letters, common letters, word lengths, and other language habits can still leak through.
It should not be used to protect real private information.
Why must a be coprime with 26?
The value a must be coprime with 26 because decryption requires the modular inverse of a.
If a shares a factor with 26, multiplication by a causes collisions. Different plaintext letters can encrypt to the same ciphertext letter. Once that happens, the original message cannot be reliably recovered.
For the standard English alphabet, the valid values of a are:
1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25
What is the difference between Caesar and Affine?
The Caesar cipher only adds a shift:
$$ E(x) = (x + b) \bmod 26 $$
The Affine cipher multiplies first, then adds a shift:
$$ E(x) = (ax + b) \bmod 26 $$
So Caesar is a special case of Affine where:
a = 1
Affine is more general than Caesar, but it is still weak by modern standards.
What is a common Affine cipher key?
A common teaching key is:
a = 5
b = 8
Using that key:
AFFINE -> IHHWVC
HELLO WORLD -> RCLLA OAPLX
This key is useful for examples because 5 is coprime with 26, and its modular inverse is easy to check:
5 x 21 = 105
105 mod 26 = 1
So:
5^-1 = 21 mod 26
Can Affine use a different alphabet size?
Yes. The same idea can work with other alphabet sizes, but the coprime rule changes.
If the alphabet has m symbols, the formula becomes:
$$ E(x) = (ax + b) \bmod m $$
The value a must be coprime with m, not necessarily 26.
For the ordinary English alphabet, m = 26.
For a different symbol set, the valid values of a would need to be recalculated.
The Real Lesson of the Affine Cipher
The Affine cipher should not be used to protect anything serious.
Not passwords.
Not private messages.
Not financial information.
Not API keys.
Not recovery phrases.
Not personal data.
Modern encryption depends on carefully analysed algorithms, large keyspaces, randomness, authentication, and formal security assumptions. The Affine cipher has none of that.
But it still earns its place.
It shows how a cipher can be a function.
It shows why reversibility matters.
It shows why some keys are invalid.
It shows why modular arithmetic is not abstract decoration.
It shows why frequency patterns are dangerous.
It shows why a larger keyspace than Caesar does not automatically mean real security.
And perhaps most importantly, it shows the reader that cryptography is not only about secret alphabets. It is about rules, transformations, constraints, inverses, and leakage.
That is a major step.
Caesar shifts the alphabet.
Atbash mirrors it.
Affine calculates it.
Once you see that, classical cryptography starts to look less like a drawer full of tricks and more like the beginning of a mathematical subject.
That is why the Affine cipher still matters.
Not because it is strong.
Because it teaches the shape of stronger ideas.