Affine Cipher Examples, Tutorials & Python Implementation

Learn Affine cipher with detailed examples and working code

Basic Encryption Examples

Simple Word Encryption

a = 5b = 8

Phrase Encryption

a = 5b = 8

Different Keys

a = 7b = 3

Identity Cipher (a=1)

a = 1b = 3

Python Implementation

def gcd(a, b):
    """Calculate Greatest Common Divisor using Euclidean algorithm"""
    while b:
        a, b = b, a % b
    return a

def mod_inverse(a, m):
    """Calculate modular multiplicative inverse using Extended Euclidean Algorithm"""
    if gcd(a, m) != 1:
        raise ValueError(f"{a} and {m} are not coprime")

    m0 = m
    x0, x1 = 0, 1

    while a > 1:
        q = a // m
        a, m = m, a % m
        x0, x1 = x1 - q * x0, x0

    return x1 + m0 if x1 < 0 else x1

def affine_encrypt(text, a, b):
    """Encrypt text using Affine cipher: E(x) = (ax + b) mod 26"""
    result = []

    for char in text:
        if char.isupper():
            x = ord(char) - ord('A')
            encrypted = (a * x + b) % 26
            result.append(chr(encrypted + ord('A')))
        elif char.islower():
            x = ord(char) - ord('a')
            encrypted = (a * x + b) % 26
            result.append(chr(encrypted + ord('a')))
        else:
            result.append(char)

    return ''.join(result)

def affine_decrypt(text, a, b):
    """Decrypt text using Affine cipher: D(y) = a⁻¹(y - b) mod 26"""
    a_inv = mod_inverse(a, 26)
    result = []

    for char in text:
        if char.isupper():
            y = ord(char) - ord('A')
            decrypted = (a_inv * (y - b)) % 26
            result.append(chr(decrypted + ord('A')))
        elif char.islower():
            y = ord(char) - ord('a')
            decrypted = (a_inv * (y - b)) % 26
            result.append(chr(decrypted + ord('a')))
        else:
            result.append(char)

    return ''.join(result)

# Example usage
plaintext = "HELLO"
a, b = 5, 8

ciphertext = affine_encrypt(plaintext, a, b)
print(f"Plaintext: {plaintext}")
print(f"Ciphertext: {ciphertext}")
print(f"Decrypted: {affine_decrypt(ciphertext, a, b)}")

Features: This implementation includes GCD calculation, modular inverse computation using the Extended Euclidean Algorithm, and both encryption and decryption functions with full error handling.

Practice Problems

Encrypt "CRYPTOGRAPHY" using a=3, b=5
Decrypt "WJPPJ" with a=5, b=8
What is the modular inverse of 7 (mod 26)?

Complete Tutorial

Understanding the Affine Cipher

The Affine cipher uses a mathematical function to encrypt text. Each letter is converted to a number (A=0, B=1, ..., Z=25), then transformed using:

E(x) = (ax + b) mod 26

Where:

  • x is the position of the plaintext letter (0-25)
  • a is the multiplicative key (must be coprime with 26)
  • b is the additive key (0-25)
  • mod 26 ensures the result stays within the alphabet

Why Must 'a' Be Coprime with 26?

The value of 'a' must be coprime with 26 (GCD(a, 26) = 1) to ensure every letter maps to a unique letter. If 'a' shares a common factor with 26, multiple letters would encrypt to the same letter, making decryption impossible.

Valid values for 'a': 1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25

Decryption Formula

To decrypt, we need the modular inverse of 'a' (denoted a⁻¹):

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

Affine Cipher Examples

Learning the affine cipher is easier with practical examples. This page provides step-by-step encryption and decryption demonstrations, complete Python code, and practice problems to test your understanding.

Basic Encryption Example

Let's encrypt the word "HELLO" using keys A=5 and B=8:

Step 1: Convert letters to numbers (A=0, B=1, ..., Z=25)

  • H=7, E=4, L=11, L=11, O=14

Step 2: Apply the encryption formula E(x) = (5x + 8) mod 26

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

Result: HELLO → RCLLA

Decryption Example

To decrypt "RCLLA" with A=5, B=8, we need the modular inverse of 5 mod 26, which is 21.

Step 1: Apply decryption formula D(y) = 21(y - 8) mod 26

  • R(17): 21×(17-8) mod 26 = 21×9 mod 26 = 189 mod 26 = 7 = H
  • C(2): 21×(2-8) mod 26 = 21×(-6) mod 26 = 21×20 mod 26 = 420 mod 26 = 4 = E
  • L(11): 21×(11-8) mod 26 = 21×3 mod 26 = 63 mod 26 = 11 = L
  • L(11): 21×(11-8) mod 26 = 21×3 mod 26 = 63 mod 26 = 11 = L
  • A(0): 21×(0-8) mod 26 = 21×(-8) mod 26 = 21×18 mod 26 = 378 mod 26 = 14 = O

Result: RCLLA → HELLO

Python Implementation

Here is a complete Python implementation of the affine cipher:

Python49 lines
Highlighting code...
1272 chars

Practice Problems

Test your understanding with these exercises:

Problem 1: Encrypt "ATTACK" with A=7, B=3

Problem 2: Decrypt "FGXOT" with A=3, B=5

Problem 3: Find the modular inverse of 7 mod 26

Problem 4: Encrypt "CIPHER" with A=11, B=15

Problem 5: What are all valid values for key A?

Answers

  1. ATTACK → EZZHFP
  2. FGXOT → HELLO
  3. The modular inverse of 7 mod 26 is 15 (because 7×15 = 105 = 4×26 + 1)
  4. CIPHER → AFLWPC
  5. Valid A values: 1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25

Try these examples in our Affine Cipher Tool or use the Calculator to verify modular inverses.

Frequently Asked Questions

How do I calculate the modular inverse?

The modular inverse of A mod 26 is a number A⁻¹ such that (A × A⁻¹) mod 26 = 1. You can find it by testing numbers 1-25 or using the extended Euclidean algorithm. Our calculator computes this automatically.

What happens if I use an invalid A value?

If A shares a common factor with 26 (like 2, 4, 6, 8, 10, 12, 13, etc.), multiple plaintext letters will map to the same ciphertext letter, making decryption impossible.

Can I implement affine cipher in other languages?

Yes! The algorithm works the same in any programming language. The key operations are modular arithmetic (% operator) and finding modular inverses. See our Python example above as a reference.

The Caesar cipher is a special case of the affine cipher where A=1. This reduces the formula to E(x) = (x + b) mod 26, which is just a simple shift.