From f1d09a57a73d55e1beb897a5163e4f549ca5e977 Mon Sep 17 00:00:00 2001 From: anishLearnsToCode Date: Tue, 25 Aug 2020 02:32:51 +0530 Subject: [PATCH] adds affine cipher --- README.md | 2 +- ciphers/AffineCipher.py | 20 ++++++++++++++++++++ ciphers/__init__.py | 1 + 3 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 ciphers/AffineCipher.py diff --git a/README.md b/README.md index 0a3a80e..582ae68 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ Algorithms from the book Cryptography & Network Security ~Behrouz A. Forouzan. S 1. Monoalphabetic Ciphers 1. [Caesar Shift Cipher](ciphers/CaesarShiftCipher.py) 1. [Multiplicative Cipher](ciphers/MultiplicativeCipher.py) - 1. Affine Cipher + 1. [Affine Cipher](ciphers/AffineCipher.py) 1. Polyalphabetic Ciphers 1. Autokey Cipher 1. [Playfair Cipher](ciphers/PlayfairCipher.py) diff --git a/ciphers/AffineCipher.py b/ciphers/AffineCipher.py new file mode 100644 index 0000000..c7b7893 --- /dev/null +++ b/ciphers/AffineCipher.py @@ -0,0 +1,20 @@ +from mathematics import multiplicative_inverse + +class AffineCipher: + def __init__(self, k_1, k_2): + self.k_1 = k_1 + self.k_2 = k_2 + + def char_to_num(self, letter): + letter = letter.lower() + return ord(letter) - ord('a') + + def encrypt(self, plaintext): + return ''.join( + [chr((self.char_to_num(letter) * self.k_1 + self.k_2) % 26 + ord('A')) for letter in plaintext.lower()]) + + def decrypt(self, ciphertext): + return ''.join( + [chr(((self.char_to_num(letter) - self.k_2) * multiplicative_inverse(self.k_1, 26)) % 26 + ord('a')) + for letter in ciphertext.lower()] + ) diff --git a/ciphers/__init__.py b/ciphers/__init__.py index c842404..e2629bd 100644 --- a/ciphers/__init__.py +++ b/ciphers/__init__.py @@ -3,3 +3,4 @@ from ciphers.PlayfairCipher import PlayFairCipher from ciphers.CaesarShiftCipher import CaesarShiftCipher from ciphers.MultiplicativeCipher import MultiplicativeCipher +from ciphers.AffineCipher import AffineCipher