Affine Cipher
Nerd Cafe
The Affine Cipher is a type of substitution cipher that uses a mathematical function to encrypt and decrypt messages. Here's a step-by-step guide with a practical example:
Step 1: Understand the Encryption Formula
The Affine Cipher encryption formula is:
Where:
𝑥 is the numerical value of a letter (e.g., A = 0, B = 1, ..., Z = 25 for English).
𝑎 and 𝑏 are keys of the cipher.
𝑎 must be coprime with 𝑚, meaning gcd(𝑎,𝑚)=1.
𝑚 is the size of the alphabet (26 for English).
Step 2: Choose Keys
Select values for 𝑎 and 𝑏. For this example:
𝑎=5
𝑏=8
𝑚=26 (English alphabet)
Step 3: Encryption Example
Plaintext: "HELLO
"
Convert Letters to Numbers:
Using 𝐴=0,𝐵=1,...,𝑍=25:
𝐻=7,𝐸=4,𝐿=11,𝑂=14
Apply Encryption Formula:
For each letter, compute:
𝐻(7):𝐸(7)=(5⋅7+8) mod 26 =43 mod 26 = 17 (R)
𝐸(4):𝐸(4)=(5⋅4+8) mod 26 =28 mod 26 = 2 (C)
𝐿(11):𝐸(11)=(5⋅11+8) mod 26 =63 mod 26 = 11 (L)
𝐿(11):𝐸(11)=(5⋅11+8) mod 26 =63 mod 26 = 11 (L)
𝑂(14):𝐸(14)=(5⋅14+8) mod 26 =78 mod 26 = 0 (A)
Encrypted Message: "RCLLA
"
Step 4: Understand the Decryption Formula
The decryption formula is:
Where:
𝑦 is the numerical value of the ciphertext letter.
𝑎inv is the modular multiplicative inverse of 𝑎 modulo 𝑚, satisfying:
Step 5: Find 𝑎inv
For 𝑎=5 and 𝑚=26:
Find 𝑎inv such that 5⋅𝑎inv≡1 mod 26.
𝑎inv=21 (calculated using the Extended Euclidean Algorithm).
Step 6: Decrypt Example
Ciphertext: "RCLLA
"
Convert Letters to Numbers:
𝑅=17, 𝐶=2, 𝐿=11, 𝐴=0
Apply Decryption Formula:
For each letter, compute:
R(17):D(17)=21⋅(17−8) mod 26=21⋅9 mod 26=189 mod 26=7 (H)
C(2):D(2)=21⋅(2−8 ) mod 26=21⋅(−6) mod 26=−126 mod 26=4 (E)
L(11):D(11)=21⋅(11−8) mod 26=21⋅3 mod 26=63 mod 26=11 (L)
L(11):D(11)=21⋅(11−8) mod 26=21⋅3 mod 26=63 mod 26=11 (L)
A(0):D(0)=21⋅(0−8) mod 26=21⋅(−8) mod 26=−168 mod 26=14 (O)
Decrypted Message: "HELLO
"
Step 7: Python Code
Here’s a Python implementation of the Affine Cipher, using the example provided. The code includes functions for both encryption and decryption.
Output:
Last updated