Affine Cipher is a relatively simple way for encrypting/decrypting data with low CPU cost but with the expensive of low level of security.
Basic Syntax: f ( X ) = α X + β (mod 26)
Note: the mod 26 means this cipher is using the English alphabet, which contains 26 characters:

- X is the correspondent value of the character that will be encrypted.
- ( α , β ) is a valid key if:
- gcd ( α , 26 ) = 1
- 1 ≤ α ≤ 25
- 0 ≤ β ≤ 25
Let’s walk through the encryption and decryption process in the Python code below that is a fork of [Link].
Encryption:
def egcd(a, b):
x,y, u,v = 0,1, 1,0
while a != 0:
q, r = b//a, b%a
m, n = x-u*q, y-v*q
b,a, x,y, u,v = a,r, u,v, m,n
gcd = b
return gcd, x, y
def modinv(a, m):
gcd, x, y = egcd(a, m)
if gcd != 1:
return None
else:
return x % m
def affine_encrypt(text, key):
'''
C = (a*P + b) % 26
'''
return ''.join([ chr((( key[0]*(ord(t) - ord('A')) + key[1] ) % 26) + ord('A')) for t in text.upper().replace(' ', '') ])
text = 'PlainText'
key = [3, 18]
print(affine_encrypt(text, key))
Decryption:
def egcd(a, b):
x,y, u,v = 0,1, 1,0
while a != 0:
q, r = b//a, b%a
m, n = x-u*q, y-v*q
b,a, x,y, u,v = a,r, u,v, m,n
gcd = b
return gcd, x, y
def modinv(a, m):
gcd, x, y = egcd(a, m)
if gcd != 1:
return None
else:
return x % m
def affine_decrypt(cipher, key):
'''
P = (a^-1 * (C - b)) % 26
'''
return ''.join([ chr((( modinv(key[0], 26)*(ord(c) - ord('A') - key[1])) % 26) + ord('A')) for c in cipher ])
cipher = 'LZSQFXEJX'
key = [3, 18]
print(affine_decrypt(cipher, key))