components p and q can be obtained from the encryption key components a and b like the following:
p = a-1 , where aa-1 mod symbol size = 1 q = - b
The decryption operation, in this case, is:
D(x) = p(x + q) mod symbol size = a-1 (x – b) mod symbol size
Please note that:
D(E(x)) = D (ax + b) mod symbol size = p(ax + b + q) mod symbol size = a-1 (ax + b – b) mod symbol size = a-1ax mod symbol size = x (as aa-1 mod symbol size = 1)
How to implement the affine cipher using Python?
The affine cipher can be implemented using Python in the following way:
import math from curses.ascii import isalpha def getKey(symbol_size): while True: a = input("A: ") a = int(a) if math.gcd(a, symbol_size) != 1: print("gcd(A, 26) should be 1. Please try again.") continue else: break while True: b = input("B: ") b = int(b) if b > symbol_size: print("B should be less than 26. Please try again.") continue else: break k = a*symbol_size + b return k def get_key_components(k, symbol_size): a = k // symbol_size b = k % symbol_size return a, b def get_decryption_key(k, symbol_size): a, b = get_key_components(k, symbol_size) p = pow(a, -1, symbol_size) q = 0 - b return p, q def encrypt(text, k, symbol_size): a, b = get_key_components(k, symbol_size) ctext = list() for i in range(len(text)): if isalpha(text[i]): s = (a * (ord(text[i]) - ord('a')) + b) % symbol_size ctext.append(chr(s + ord('a'))) else: ctext.append(text[i]) return "".join(ctext) def decrypt(ctext, p, q, symbol_size): text = list() for i in range(len(ctext)): if isalpha(ctext[i]): s = (p * ((ord(ctext[i]) - ord('a')) + q)) % symbol_size text.append(chr(s + ord('a'))) else: text.append(ctext[i]) return "".join(text) SYMBOL_SIZE = 26 key = getKey(SYMBOL_SIZE) print("Your key is ", key) plaintext = input("Plaintext: ") ciphertext = encrypt(plaintext, key, SYMBOL_SIZE) print(ciphertext) P, Q = get_decryption_key(key, SYMBOL_SIZE) decrypted_text = decrypt(ciphertext, P, Q, SYMBOL_SIZE) print(decrypted_text)






0 Comments