Overview

The Affine cipher is a type of simple substitution cipher and as such uses a fixed ciphertext alphabet over the entire message. The ciphertext alphabet gets derived from the plaintext alphabet using an affine mathematical function (also called linear function) as the key.

Affine function

Simply put, an affine function is the process of multiplying a value xx by a constant aa, then adding a constant bb to it.

As we want to make sure we don’t leave the scope of our alphabet with length mm, we apply the mod m\text{mod }m operation at the end (we subtract mm from the result until we get a value smaller than mm).

Hence, an affine function ff can be represented as f(x)=ax+b mod mf(x)=ax+b\text{ mod }m.

How does Affine cipher work?

For this example, we use the Latin alphabet A-Z with length m=26m=26 as our plaintext alphabet and the affine function f(x)=5x+8f(x)=5x+8 with a=5,b=8a=5,b=8.

First, we map each letter in the alphabet to its numeric equivalent by taking its position in the alphabet (starting with 0), like so:

A ->  0   B ->  1   C ->  2   D ->  3   E ->  4   F ->  5   G ->  6   H ->  7   I ->  8   J ->  9   K -> 10   L -> 11   M -> 12   N -> 13   O -> 14   P -> 15   Q -> 16   R -> 17   S -> 18   T -> 19   U -> 20   V -> 21   W -> 22   X -> 23   Y -> 24   Z -> 25
Mapping letters in the Latin alphabet to positions 0-25

Now we apply the affine function ff to each of the values above (modulo mm):

A ->  8   B -> 13   C -> 18   D -> 23   E ->  2   F ->  7   G -> 12   H -> 17   I -> 22   J ->  1   K ->  6   L -> 11   M -> 16   N -> 21   O ->  0   P ->  5   Q -> 10   R -> 15   S -> 20   T -> 25   U ->  4   V ->  9   W -> 14   X -> 19   Y -> 24   Z ->  3
Mapping letters in the Latin alphabet to their ciphertext letter positions 0-25

Finally, we convert back the numbers to their letter equivalents:

A ->  I   B ->  N   C ->  S   D ->  X   E ->  C   F ->  H   G ->  M   H ->  R   I ->  W   J ->  B   K ->  G   L ->  L   M ->  Q   N ->  V   O ->  A   P ->  F   Q ->  K   R ->  P   S ->  U   T ->  Z   U ->  E   V ->  J   W ->  O   X ->  T   Y ->  Y   Z ->  D
Mapping letters in the Latin alphabet to their respective ciphertext letters

This gives us the map to encrypt and decrypt any message using the Affine cipher key f(x)=5x+8f(x)=5x+8 and the Latin alphabet A-Z.

See also

Resources