Skip to main content
The National Cipher Challenge

Reply To: How does an affine shift cipher work?

#156190
Crackerjack
Participant

Do you understand how the encryption and numbers mod 26 work? One way to think about the affine cipher is just a caesar cipher with an extra step.

Caesar, as a reminder: turn each letter into a number (A=0, B=1, … Z=25), add the shift, and “wrap around” past Z.
E.g. with a shift of 5: H=7 —> 7+5=12 → M

“Wrapping around” just means that if the number is 26 or more, take away 26 until it’s between 0 and 25. That’s the same as taking the remainder when you divide by 26. Negative numbers work the other way: add 26 until you’re back in range. The formal term for this is modulo 26, or “mod 26” for short.

Affine: we do exactly the same thing, but first multiply by a number a, then apply the shift b.
E.g. with a=3 and b=5: H=7—> 3*7=21 —> 21+5=26 —> wrap around —> 0 —> A

In Caesar, every letter moves by the same distance, so the alphabet just slides along. With affine, the multiplication scrambles the order of the alphabet before the shift, which is why you can’t crack it just by trying all 26 shifts.

If you look at the BOSS tools, you’ll notice that for affine you can only pick the odd numbers except 13 (1, 3, 5, … 11, 15, … 25). With any other value, two letters would encrypt to the same letter, and you couldn’t decrypt the message.
For the sake of argument, pick an even multiplier, like a=2. Any number times 2 is even, and wrapping around by 26 (also even) keeps it even. So every letter lands on an even number, which leaves only 13 possible results for 26 letters:
A=0 —> 2*0=0
N=13 —> 2*13=26 —> wrap —> 0

A and N become the same letter, so when you decrypt you can’t tell which one it was (13 fails for the same reason: 13 × 2 = 26 wraps straight back to 0)

Decrypting means doing the steps in reverse. So undo the shift first, then undo the multiplication. Undoing the shift is easy: just subtract b.
Undoing the multiplication is a bit trickier, because you can’t divide normally. Instead, you multiply by an “undo” number (formally called the inverse of a), which is the number that, when multiplied by a, wraps round to exactly 1.
Using our earlier example (a=3, b= 5), decrypting 
A = 0 —> 0 − 5 = −5
−5 is less than 0, so wrap around by adding 26: −5+26=21

Encryption multiplied by 3, so we multiply by its undo number 9 (9*3=27, which wraps round to 1):
21*9=189

189 is too big, so wrap around: 189 − 26*7 = 189-182=7 is H, which is exactly the letter we encrypted! To find the undo number for other values of a, just try multiplying a by 1, 3, 5, 7… until the answer wraps round to 1.

Does that make sense? Is there anything specific you’re confused about from the training resources?

Report a problem