# Demystifying Affine cipher

The Affine cipher maps each letter in an alphabet to its numeric equivalent, encrypts it using a linear mathematical function, and converts it back to a letter.

## 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 $x$ by a constant $a$, then adding a constant $b$ to it.

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

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

## How does Affine cipher work?

For this example, we use the Latin alphabet A-Z with length $m=26$ as our plaintext alphabet and the affine function $f(x)=5x+8$ with $a=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:

Now we apply the affine function $f$ to each of the values above (modulo $m$):

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

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