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