Lesson 4 of 15
Affine Cipher
Affine Cipher
The affine cipher generalizes the Caesar cipher with a linear transformation over .
Encryption
where is the letter value (A=0, …, Z=25), and are integer keys. must satisfy so that decryption is possible.
Valid values of : 1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25 (12 choices).
Decryption
where is the modular inverse of modulo 26.
Modular Inverse via Extended GCD
The Extended Euclidean Algorithm finds integers such that . When , we have , so is the modular inverse.
def extended_gcd(a, b):
if b == 0: return a, 1, 0
g, x, y = extended_gcd(b, a % b)
return g, y, x - (a // b) * y
def mod_inverse(a, m):
g, x, _ = extended_gcd(a, m)
return x % m # ensure positive
mod_inverse(5, 26) # 21, since 5*21 = 105 = 4*26+1
Example (, )
| Plaintext | H(7) | E(4) | L(11) | L(11) | O(14) |
|---|---|---|---|---|---|
| mod 26 | 17 | 2 | 11 | 11 | 0 |
| Ciphertext | R | C | L | L | A |
Your Task
Implement:
mod_inverse(a, m)using extended GCDaffine_encrypt(text, a, b)— apply affine transformation, preserve case, skip non-alphaaffine_decrypt(text, a, b)— apply inverse transformation
Python runtime loading...
Loading...
Click "Run" to execute your code.