Skip to content

Instantly share code, notes, and snippets.

@zacps
Created October 26, 2017 03:43
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 zacps/5a815eed48d908cc4dc79bc645e32a78 to your computer and use it in GitHub Desktop.
Save zacps/5a815eed48d908cc4dc79bc645e32a78 to your computer and use it in GitHub Desktop.
import string
def get_int(prompt, minimum, maximum):
val = input(prompt)
try:
val = int(val)
except ValueError:
print("Please enter an int between {} and {}".format(minimum, maximum))
return None
else:
return val
def trans_str_tbl(shift):
#Lowercase
low_alphabet = string.ascii_lowercase
low_shifted_alphabet = low_alphabet[shift:] + low_alphabet[:shift]
#Uppercase
upper_alphabet = string.ascii_uppercase
upper_shifted_alphabet = upper_alphabet[shift:] + upper_alphabet[:shift]
#Make dictionary
table = str.maketrans(low_alphabet, low_shifted_alphabet)
table.update(str.maketrans(upper_alphabet, upper_shifted_alphabet))
return table
def en_caesar(plaintext, key):
table = trans_str_tbl(key)
return plaintext.translate(table)
def de_caesar(ciphertext, key):
table = trans_str_tbl(-key)
return ciphertext.translate(table)
def force_caesar(ciphertext, wordlist):
accuracy = {key: 0 for key in range(25)}
result = {key: None for key in range(25)}
for i in range(25):
result[i] = de_caesar(ciphertext, i)
for word in result[i].split():
if word.lower() in wordlist.split():
accuracy[i] += 1
if accuracy[i] == len(result[i].split()):
return result[i]
return result[list(accuracy.values()).index(max(list(accuracy.values())))]
if __name__ == "__main__":
command = input("Do you want to 'decrypt', 'encrypt', or 'force'? ").lower().strip()
if command == "encrypt":
text = input("Enter the text to encrypt: ")
while True:
key = get_int("Enter the key, or shift, of the text (1-25): ", 0, 25)
if key is not None:
break
print(en_caesar(text, key))
elif command =="decrypt":
text = input("Enter the text to decrypt: ")
key = int(input("Enter the key, or shift, of the text (1-25): "))
print(de_caesar(text, key))
elif command == "force":
wordlist = input("Wordlist path: ")
print(force_caesar(input("Ciphertext: "), open(wordlist).read()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment