#Caesar cipher import random #the plaintext string is assumed to consist #of lower-case letters #with no spaces or other punctuation #The key k is an integer--we only use the value of k #mod 26. def caesar_encrypt(plaintext,k): ciphertext = '' for ch in plaintext: ciphertext += shiftletter(ch,k) return ciphertext #The actual computation of adding k mod 26 to a lower-case #letter value is done here. Note we use functions chr and ord #to convert between characters and their ASCII encodings, and #use ord('a') as an offset so that 'a' corresponds to 0, 'b' to 1, #etc. def shiftletter(letter,k): return chr(ord('a')+(ord(letter)-ord('a')+k)%26) def caesar_decrypt(ciphertext,k): return caesar_encrypt(ciphertext,-k) #Return a list of all decryptions of the given ciphertext under #every possible key. Since there are only 26 of them, visual inspection #reveals the correct plaintext. def all_decryptions(ciphertext): dec_list=[] for k in range(26): dec_list.append(caesar_encrypt(ciphertext,k)) return dec_list #Run this function to see a demonstration def caesar_demo(): plaintext=raw_input('Enter plaintext string\n') #convert to lower case and strip non-letters plaintext=plaintext.lower() newplaintext='' for ch in plaintext: if ord('a')<=ord(ch)<=ord('z'): #yes, this is legal Python! newplaintext+= ch print 'Modified plaintext:' print newplaintext print print 'Encrypt under random key' key=random.randint(0,25) ciphertext = caesar_encrypt(newplaintext,key) print print ciphertext print print 'Decrypt under every possible key' print decs=all_decryptions(ciphertext) for text in decs: print text