Skip to content

Instantly share code, notes, and snippets.

@kamaci
Created April 27, 2023 20:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamaci/d6349283582138e3d9efc1ea84f2ee59 to your computer and use it in GitHub Desktop.
Save kamaci/d6349283582138e3d9efc1ea84f2ee59 to your computer and use it in GitHub Desktop.
Shift Cipher
import string
class ShiftCipher:
def __init__(self, shift_size=3):
self.shift_size = shift_size % 26
self.shifted = []
for decrypted in string.ascii_uppercase:
encrypted = chr((ord(decrypted) - ord('A') + self.shift_size) % 26 + ord('A'))
self.shifted.append(encrypted)
def encrypt(self, plain_text):
plain_text = plain_text.upper()
cipher_text = [self.shifted[string.ascii_uppercase.index(p)] for p in plain_text]
cipher_text = ''.join(cipher_text)
return cipher_text
def decrypt(self, cipher_text):
cipher_text = cipher_text.upper()
plain_text = [string.ascii_uppercase[self.shifted.index(c)] for c in cipher_text]
plain_text = ''.join(plain_text)
return plain_text
@staticmethod
def crack(ciphertext, plain_text):
for shift_size in range(26):
shift_cipher = ShiftCipher(shift_size)
decrypted_text = shift_cipher.decrypt(ciphertext)
if decrypted_text == plain_text:
return shift_size
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment