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:
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
- ATTACK → EZZHFP
- FGXOT → HELLO
- The modular inverse of 7 mod 26 is 15 (because 7×15 = 105 = 4×26 + 1)
- CIPHER → AFLWPC
- 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.
How is affine cipher related to Caesar cipher?
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.