Skip to main content
Basic Classic Symmetric Beginner

The Affine Cipher

Learn about the Affine cipher, a generalization of the Caesar cipher that combines multiplication and addition to create a larger, but still breakable, keyspace.

PL
Pashalis Laoutaris
August 21, 2026
14 min read

Interactive Affine Cipher Visualizer

🔐 Affine Cipher Visualizer

5
Enter text and click a button to start!
HELLO

The Affine Cipher: Caesar with Multiplication

Introduction

The Affine cipher takes the Caesar cipher’s single idea, shifting every letter by a fixed amount, and generalizes it with a second operation: multiplication. Instead of a single shift key, the Affine cipher uses two keys, combining them into one linear function applied to each letter’s position in the alphabet. The name comes from mathematics: an “affine transformation” is a linear scaling (multiplication) combined with a translation (addition). Those are exactly the two operations this cipher applies to every letter. The result is a monoalphabetic substitution cipher with a considerably larger keyspace than Caesar, while remaining simple enough to compute by hand.

Table of Contents

How the Affine Cipher Works

Each letter is first converted to its numeric position in the alphabet (A=0, B=1, …, Z=25). Encryption then applies a simple linear function to that number:

E(x) = (a·x + b) mod 26

Here, a and b are the two parts of the key: a scales the letter’s position (the “multiplicative” key), and b shifts the result (the “additive” key), exactly the shift used by the Caesar cipher on its own. The result is reduced modulo 26 and converted back into a letter.

Example with a = 5, b = 8:

  • H (x=7): (5×7 + 8) mod 26 = 43 mod 26 = 17 → R
  • E (x=4): (5×4 + 8) mod 26 = 28 mod 26 = 2 → C
  • L (x=11): (5×11 + 8) mod 26 = 63 mod 26 = 11 → L
  • L (x=11): → L
  • O (x=14): (5×14 + 8) mod 26 = 78 mod 26 = 0 → A

“HELLO” → “RCLLA”

Non-letter characters (spaces, punctuation, digits) are conventionally stripped out before encryption. The function above is only defined for the 26 letter positions, so the visualizer (like the rest of this series) works on a sanitized, letters-only version of your input.

Interactive Visualizer

Try it above. Pick a valid value for key A from the dropdown, choose a shift for key B, and watch each letter transform through the linear function in real time.

Why Key A Can’t Be Just Any Number

Not every value works for a. For the cipher to be reversible, every ciphertext letter has to map back to exactly one plaintext letter. That requires a to share no common factors with 26 other than 1, a property called being coprime with 26 (formally, gcd(a, 26) = 1).

Since 26 = 2 × 13, a must avoid all multiples of 2 and all multiples of 13. This leaves exactly 12 valid values for a: 1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, and 25. (This count isn’t a coincidence. It’s exactly Euler’s totient of 26, written φ(26) = 12: the totient function counts how many numbers from 1 to n share no common factor with n, which is precisely the condition a must satisfy.)

If a weren’t coprime with 26 (say, a = 2), then multiple different plaintext letters would collide onto the same ciphertext letter. Concretely, with a = 2, both A (x=0) and N (x=13) encrypt to the exact same letter for any value of b, since 2×0 = 0 and 2×13 = 26 ≡ 0 (mod 26). The two inputs land on the same result before b even gets added. Once a collision like this exists, decryption becomes ambiguous: seeing that ciphertext letter, there’s no way to tell whether the original was A or N. This is why the visualizer above only offers valid choices for key A.

The key b, by contrast, has no such restriction. Any value from 0 to 25 works, exactly like a Caesar shift.

The same logic generalizes beyond the 26-letter alphabet used here: for an alphabet of size m, the multiplicative key must satisfy gcd(a, m) = 1, and the number of valid choices is φ(m).

Decryption: Undoing the Linear Function

To decrypt, the linear function must be inverted algebraically:

D(y) = a⁻¹(y - b) mod 26

Here, a⁻¹ is the modular multiplicative inverse of a modulo 26: the number that satisfies (a × a⁻¹) mod 26 = 1. This is exactly the same requirement that makes a valid in the first place: only numbers coprime with 26 have a modular inverse mod 26 at all.

For example, if a = 5, its modular inverse is 21, because 5 × 21 = 105 = 4×26 + 1, so 105 mod 26 = 1. The visualizer computes this inverse automatically whenever you decrypt.

Finding it by hand: for a small modulus like 26, the simplest approach is trial multiplication. Try a × 1, a × 2, a × 3, ... mod 26 until the result is 1. For a = 5: 5×1=5, 5×2=10, 5×3=15, …, 5×21=105 ≡ 1. So 21 is the answer, found after 21 quick checks at worst. For larger moduli, trial multiplication would take too long. The standard efficient method there is the extended Euclidean algorithm. It computes the same modular inverse in a handful of division steps, regardless of how large the modulus is.

A Worked Example

Continuing the example above, decrypting “RCLLA” with a = 5, b = 8 (so a⁻¹ = 21):

  • R (y=17): 21×(17 - 8) mod 26 = 21×9 mod 26 = 189 mod 26 = 7 → H
  • C (y=2): 21×(2 - 8) mod 26 = 21×(-6) mod 26 = -126 mod 26 = 4 → E
  • L (y=11): 21×(11 - 8) mod 26 = 21×3 mod 26 = 63 mod 26 = 11 → L
  • L (y=11): → L
  • A (y=0): 21×(0 - 8) mod 26 = 21×(-8) mod 26 = -168 mod 26 = 14 → O

“RCLLA” → “HELLO”, exactly recovering the original message.

For reference, here’s the complete substitution alphabet that a = 5, b = 8 produces. Every letter’s fate is fixed the moment the key is chosen:

Plain A B C D E F G H I J K L M
Cipher I N S X C H M R W B G L Q
Plain N O P Q R S T U V W X Y Z
Cipher V A F K P U Z E J O T Y D

Notice L and Y happen to map to themselves under this particular key. That’s a coincidence of the arithmetic for this specific a and b, not a general property of the cipher.

Pros and Cons Analysis

Advantages Disadvantages
Larger Keyspace than Caesar: 12 valid values for a × 26 values for b = 312 possible keys, far larger than Caesar’s handful of shifts (25, or 26 if you count the null shift) Still Trivially Brute-Forceable: 312 keys is nothing for a computer, or even a patient human, to exhaust
Introduces Modular Inverses: A clean, practical introduction to modular multiplicative inverses, a concept that reappears throughout cryptography (including in RSA) Frequency Analysis Still Works: As a monoalphabetic substitution, it preserves the source language’s letter-frequency profile just like Caesar and Atbash
Generalizes Caesar: Demonstrates that Caesar is just the special case where a = 1, connecting the two ciphers conceptually Restricted Key Choices Leak Information: Only 12 of the 26 possible values for a are usable, which shrinks the effective keyspace an attacker has to search and is itself a hint about the cipher’s structure to anyone attacking it
Easy to Compute by Hand: Requires only multiplication, addition, and a modulo operation No Real-World Security: Offers no protection against any adversary with basic cryptanalysis tools

Cryptanalysis and Breaking the Affine Cipher

With only 312 possible keys, a brute-force attack is trivial for any computer, and even fully manageable by hand with some patience. But the Affine cipher can be broken even faster with a known-plaintext attack. If an attacker recovers just two plaintext-ciphertext letter pairs, they can set up two linear equations and solve directly for a and b using modular arithmetic, no brute force required. The two pairs do need to involve two different plaintext letters, though. If both known pairs happen to give the same plaintext letter, the two equations collapse into one, and there isn’t enough independent information to solve for both a and b.

Frequency analysis also applies exactly as it does to the Caesar cipher. Affine is a monoalphabetic substitution, so the most frequent ciphertext letter is very likely the encryption of the most frequent plaintext letter (E, in English). That gives an attacker a strong first guess to narrow down the keyspace immediately.

Affine vs. Caesar vs. Atbash

All three are classic monoalphabetic substitution ciphers built from the same family of ideas, but they differ in generality:

  • Caesar cipher: E(x) = x + b mod 26, the special case of Affine where a = 1.
  • Atbash cipher: E(x) = 25 - x mod 26, the special case of Affine where a = -1 (equivalent to 25) and b = 25.
  • Affine cipher: E(x) = a·x + b mod 26, the general form that contains both of the above as special cases, plus 310 other key combinations.

This makes the Affine cipher a useful bridge in a cryptography curriculum: it shows students that Caesar and Atbash aren’t unrelated tricks, but two points on the same underlying mathematical family.

Modern Relevance

Like its simpler relatives, the Affine cipher has no place in real-world security, but it remains valuable as:

  • A teaching tool for introducing modular multiplicative inverses and linear congruences before students encounter them again in RSA and other modern cryptosystems.
  • A stepping stone between single-operation ciphers (Caesar, Atbash) and the more general polyalphabetic ciphers (like Vigenère) that followed historically.
  • A programming exercise that requires implementing the extended Euclidean algorithm or a similar method to compute modular inverses.
  • A natural textbook example: the Affine cipher tends to appear in cryptography courses right after modular arithmetic is introduced, since it’s the simplest possible cipher that actually requires a modular inverse to decrypt. That’s a mathematical structure students will meet again, at a much larger scale, in RSA and its modular exponentiation. Readers curious where a matrix generalization of this same linear idea leads should see the Hill cipher, which extends the same “multiply-and-add mod m” structure from single letters to whole blocks of letters at once.

Python Implementation

The visualizer above computes everything in JavaScript. Here’s the same linear function and its modular inverse in Python, matching the worked example above with a = 5, b = 8:

from math import gcd

def mod_inverse(a, m=26):
    """Finds a^-1 mod m by trial multiplication, fine for a small modulus like 26."""
    for x in range(1, m):
        if (a * x) % m == 1:
            return x
    raise ValueError(f"{a} has no inverse mod {m}")

def affine_encrypt(text, a, b):
    if gcd(a, 26) != 1:
        raise ValueError("key 'a' must be coprime with 26")
    text = ''.join(c for c in text.upper() if c.isalpha())
    return ''.join(chr((a * (ord(c) - ord('A')) + b) % 26 + ord('A')) for c in text)

def affine_decrypt(text, a, b):
    a_inv = mod_inverse(a)
    return ''.join(chr((a_inv * (ord(c) - ord('A') - b)) % 26 + ord('A')) for c in text)

if __name__ == "__main__":
    a, b = 5, 8
    plaintext = "HELLO"

    ciphertext = affine_encrypt(plaintext, a, b)
    recovered = affine_decrypt(ciphertext, a, b)

    print(f"Plaintext:  {plaintext}")
    print(f"Ciphertext: {ciphertext}")
    print(f"Recovered:  {recovered}")

This prints HELLORCLLAHELLO, matching the by-hand arithmetic worked through earlier in this article letter by letter.

Limitations

This implementation is deliberately minimal:

  • mod_inverse is brute-force. Trial multiplication is fine for modulus 26, but it doesn’t scale. Real cryptosystems needing modular inverses over much larger numbers, RSA among them, use the extended Euclidean algorithm instead.
  • No validation of the visualizer’s key restriction beyond a single check. affine_encrypt raises an error for a non-coprime a, but it doesn’t explain which factor of 26 caused the collision, information the visualizer’s dropdown sidesteps by only offering valid values in the first place.
  • English letters only, formatting is lost. Spaces, punctuation, and case are stripped before encryption, exactly like the visualizer, so the round trip doesn’t reproduce the original message’s appearance.
  • Not intended for real security. 312 keys is trivial to exhaust regardless of implementation quality; this code exists to demonstrate the linear function and its inverse, not to protect data.

Conclusion

The Affine cipher shows what happens when you combine two simple operations, multiplication and addition, into a single cipher: a modestly larger keyspace, a cleaner mathematical structure, and a natural generalization that unifies the Caesar and Atbash ciphers as special cases. Its real value today is pedagogical: it’s often the first place students meet the modular multiplicative inverse, a concept that resurfaces constantly throughout modern cryptography.

FAQ

What is the Affine Cipher?

The Affine cipher is a substitution cipher that transforms each letter’s alphabet position x using the function E(x) = (a·x + b) mod 26, where a and b are the two parts of the key.

Why must key A be coprime with 26?

Because only values coprime with 26 have a modular multiplicative inverse mod 26, which is required to reverse the encryption during decryption. If a weren’t coprime with 26, multiple plaintext letters would map to the same ciphertext letter, making decryption ambiguous.

How many possible keys does the Affine cipher have?

  1. That’s the 12 valid values for a (numbers from 1-25 coprime with 26) multiplied by the 26 possible values for b.

Is the Affine Cipher more secure than the Caesar Cipher?

Marginally. Its keyspace is about 12 times larger, but 312 keys is still trivial to brute-force by computer. It also remains just as vulnerable to frequency analysis, since it’s still a monoalphabetic substitution.

How does the Caesar Cipher relate to the Affine Cipher?

The Caesar cipher is a special case of the Affine cipher where a = 1, reducing the function to E(x) = x + b mod 26, a pure shift with no multiplication.

How do I compute the modular inverse by hand?

For a small modulus like 26, just try multiplying a by 1, 2, 3, and so on (mod 26) until the result is 1. That multiplier is the inverse. For example, 5 × 21 = 105 ≡ 1 (mod 26), so 21 is the inverse of 5. For larger moduli, the extended Euclidean algorithm finds the same answer in only a few steps, without needing to check every candidate.

References

  1. Wikipedia. “Affine cipher.” Available at: https://en.wikipedia.org/wiki/Affine_cipher

  2. Practical Cryptography. “Affine Cipher.” Available at: http://practicalcryptography.com/ciphers/affine-cipher/

  3. GeeksforGeeks. “Affine Cipher.” Available at: https://www.geeksforgeeks.org/affine-cipher/