Algebra · Modular arithmetic

Affine Cipher Lab

Every letter has a number.

See how the affine cipher hides a message with a little algebra, try it on your own words, then practice encoding and decoding by hand with your answers checked letter by letter.

Download the study guide PDF · 8 pages · 480 KB

Background

What is the affine cipher?

The affine cipher is a substitution cipher: every letter is always replaced by the same other letter. Each letter becomes a number (A = 0, B = 1, and so on up to Z = 25), a formula changes the number, and the result becomes a letter again. The two numbers a and b in the formula are the key.

Encode E(x) = (ax + b) mod 26 Multiply by a, add b, then keep the remainder after dividing by 26.
Decode D(y) = a inverse times (y minus b) mod 26 Subtract b, multiply by a inverse, then keep the remainder.
  • Caesar and Atbash. The Caesar cipher is the special case a = 1, which shifts every letter b places along the alphabet. Julius Caesar is said to have shifted by 3, so b = 3. Atbash, which reverses the alphabet (A becomes Z, B becomes Y), is a = 25, b = 25.
  • Not every a works. a must share no factor with 26, which is written gcd(a, 26) = 1. Otherwise two letters encode to the same letter and the message can't be decoded. With a = 2, for example, A (0) and N (13) both become A. That leaves 12 usable values: 1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25.
  • Easy to break. 12 choices for a and 26 for b give only 12 × 26 = 312 keys, so anyone can break the cipher by trying every key, or by counting how often each letter appears (frequency analysis, a method described by the 9th-century scholar al-Kindi). The affine cipher is for learning, not for keeping secrets.
  • Decoding needs an inverse. a inverse is the inverse of a mod 26: the number that gives a remainder of 1 when you multiply it by a and divide by 26. For a = 7 it is 15, because 7 × 15 = 105 = 4 × 26 + 1.

Letters and their numbers

Each letter from A to Z with its number from 0 to 25
LetterABCDEFGHIJKLMNOPQRSTUVWXYZ
Number012345678910111213141516171819202122232425

Free tool

Try the cipher

Choose a key and type a message. The result changes as you type.

Encoded message

RLOI PH UVY

Practice

Practice encoding

Encode the message by hand with this key, type your answer, then check it.

Practice

Practice decoding

Decode the message by hand with this key, type your answer, then check it.