#!/usr/bin/python def caesar(phrase, shift): letters = 'abcdefghijklmnopqrstuvwxyz' trans = dict([(letters[i], letters[(i + shift) % 26]) for i in range(26)]) outstring = '' for a in phrase: if trans.has_key(a.lower()): if a.islower(): outstring += trans[a] else: outstring += trans[a.lower()].upper() else: outstring += a return outstring def uncaesar(phrase, dictionary='/usr/share/dict/words'): likely = [0 for a in range(26)] for i in range(26): words = caesar(phrase, i).split() for word in words: for line in open(dictionary).readlines(): if word.lower() == line.lower().strip(): likely[i] += 1 break shift, high = -1, -1 for i in range(26): if likely[i] > high: shift = i high = likely[i] return caesar(phrase, shift) phrase = raw_input("Phrase to encrypt? ") shift = int(raw_input("Shift by? ")) shifted = caesar(phrase, shift) print "Encrypted:", shifted print "Decrypting..." shifted = uncaesar(shifted) print "Decrypted:", shifted if shifted == phrase: print "Success!" else: print "Fail!"