Skip to content

Instantly share code, notes, and snippets.

@pmrowla
Created September 16, 2015 06:28
Show Gist options
  • Save pmrowla/403e0d68cdba53bd40e0 to your computer and use it in GitHub Desktop.
Save pmrowla/403e0d68cdba53bd40e0 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
from __future__ import unicode_literals
def check_cipher(plaintexts):
winner = None
winner_count = 0
winner_shift = 0
for plaintext, shift in plaintexts:
e_count = 0
for p in plaintext:
if p == 'e':
e_count += 1
if e_count > winner_count:
winner = plaintext
winner_count = e_count
winner_shift = shift
print 'Plaintext: {}'.format(winner)
print 'Shift: {}'.format(winner_shift)
def decrypt_caesar(ciphertext, shift):
"""return a decrypted version of a Caesar cipher encrypted ciphertext"""
shift %= 26
plaintext = []
for c in ciphertext.lower():
if c.isalpha():
p = ord(c) + shift
if p > ord('z'):
p -= 26
plaintext.append(chr(p))
else:
plaintext.append(c)
return ''.join(plaintext)
def brute_caesar(cipher_encrypt):
plaintexts = []
for i in range(1, 26):
plaintexts.append((decrypt_caesar(cipher_encrypt, i), i))
return plaintexts
def main():
cipher_encrypt = raw_input("Please enter encrypted text: ")
shift = raw_input("Enter shift amount. Enter \"all\" for brute force: ")
if shift == "all":
possible_plaintexts = brute_caesar(cipher_encrypt)
check_cipher(possible_plaintexts)
else:
print decrypt_caesar(cipher_encrypt, int(shift))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment