An affine cipher is a cipher belonging to the group of monoalphabetic substitution ciphers.

The monoalphabetic cipher family has one very important feature, namely one letter of the open alphabet corresponds to exactly one letter of the secret alphabet. The encryption function looks like this:
$$ f(x)=ax+b\mod \ m$$
**x** - encrypted letter,

**(a,b)** - key,

**m** - number of letters in the alphabet (usually 26 because that's the number of letters in the English language).

It is easy to notice that if a = 1 then we are dealing with an ordinary shift (as in Caesar's cipher).

The affine cipher makes sense only when the affine function f is not equal, i.e. when for any y belonging to the set of classes of residuals \begin{align} {\mathbb {Z} }_{m}\end{align} formula
$$ ax+b\equiv y\mod \ m$$
has at most one solution for the variable x. Let's write our equation as follows:
$$ ax\equiv y-b\mod \ m$$

Note that when y values run across the whole set $$ {\mathbb{Z}}_{m} $$, then y-b values are running out, that is, it is enough if we examine the solvability of equations
$$ ax\equiv y\mod \ m$$
for $$ y\in {\mathbb {Z} }_{m}$$

This equation has exactly one solution for everyone
$$ y\in {\mathbb {Z} }_{m}$$
if and only if
$$\rm {NWD}(a,m)=1$$ (where gcd is the greatest common divisor of two numbers).

The decryption function for this cipher looks like this :
$$ d(y)=a^{-1}*(y-b)\mod m$$
where $$ a^{-1}$$ is the reciprocal of ** a ** in a ring $$ {\mathbb {Z} }_{26} $$
The formula results from the calculations:
\begin{aligned}{\mbox{D}}({\mbox{E}}(x))&=a^{-1}({\mbox{E}}(x)-b)\mod {m}\\&=a^{-1}(((ax+b)\mod {m})-b)\mod {m}\\&=a^{-1}(ax+b-b)\mod {m}\\&=a^{-1}ax\mod {m}\\&=x\mod {m}.\end{aligned}
More on: Wikipedia - Affine cipher