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:

E(x)=(a.x+b)β€…β€Šβ€…β€Šmodβ€…β€Šβ€…β€ŠmE(x)=(a.x+b)\;\;mod\;\;m

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:

E(x)=(5.x+8)β€…β€Šβ€…β€Šmodβ€…β€Šβ€…β€Š26E(x)=(5.x+8)\;\;mod\;\;26
  • 𝐻(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:

D(y)=ainv.(yβˆ’b)β€…β€Šβ€…β€Šmodβ€…β€Šβ€…β€ŠmD(y)=a_{inv}.(y-b)\;\;mod\;\;m

Where:

  • 𝑦 is the numerical value of the ciphertext letter.

  • π‘Žinv is the modular multiplicative inverse of π‘Ž modulo π‘š, satisfying:

a.ainv≑1β€…β€Šβ€…β€Šmodβ€…β€Šβ€…β€Šma.a_{inv}\equiv 1\;\;mod\;\;m

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:

D(y)=21.(yβˆ’8)β€…β€Šβ€…β€Šmodβ€…β€Šβ€…β€Š26D(y)=21.(y-8)\;\;mod\;\;26
  • 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