19 September 2011

Python script to decipher Caesar ciphers

    Caesar cipher is a simple, widely used encryption technique. It is a kind of substitution cipher in which each letter in the plain-message is replaced by a letter some fixed number positions down the alphabet.

Caesar3.svg
Read more - http://en.wikipedia.org/wiki/Caesar_cipher

Example 
Ciphertext: wkh txlfn eurzq ira mxpsv ryhu wkh odcb grj
Plaintext: the quick brown fox jumps over the lazy dog
view raw example hosted with ❤ by GitHub

Today, I prepared a simple python program to do this for solving a puzzle from Kryptos - an online treasure hunt conducted as a part of MEC EXCEL 2011.


Then I added some more features to it like handling both uppercase and lowercase & ignoring symbols. Here's it.
#!/usr/bin/python
#Date: Sept 19, 2011
#Filename: caesar.py
#Code for deciphering Caesar-Cipher
#Author: Jithu Sunny
#Blog: http://jithusunnyk.blogspot.com/
#Email: jithusunnyk@gmail.com
def shift(str, n):
'''Forms the new string by shifting all characters in str by n places'''
new = ''
for c in str:
if c.isalpha():
num = ord(c) + n
if c.islower():
if num < 123:
new += chr(num)
else:
new += chr(num - 26)
elif c.isupper():
if num < 91:
new += chr(num)
else:
new += chr(num - 26)
else:
new += c
return new
def combi(str):
'''Prints all 25 possible plain-messages'''
for i in range(1, 26):
print shift(str, i)
str = raw_input('Enter the cipher: ')
combi(str)
view raw caesar.py hosted with ❤ by GitHub
Sample Output
jisuka@HCL:~/git/Python/Caesar$ python caesar.py
Enter the cipher: "Jan hxd fjclqrwp luxbnuh?"
"Kbo iye gkdmrsxq mvycovi?"
"Lcp jzf hlenstyr nwzdpwj?"
"Mdq kag imfotuzs oxaeqxk?"
"Ner lbh jngpuvat pybfryl?"
"Ofs mci kohqvwbu qzcgszm?"
"Pgt ndj lpirwxcv radhtan?"
"Qhu oek mqjsxydw sbeiubo?"
"Riv pfl nrktyzex tcfjvcp?"
"Sjw qgm osluzafy udgkwdq?"
"Tkx rhn ptmvabgz vehlxer?"
"Uly sio qunwbcha wfimyfs?"
"Vmz tjp rvoxcdib xgjnzgt?"
"Wna ukq swpydejc yhkoahu?"
"Xob vlr txqzefkd zilpbiv?"
"Ypc wms uyrafgle ajmqcjw?"
"Zqd xnt vzsbghmf bknrdkx?"
"Are you watching closely?"
"Bsf zpv xbudijoh dmptfmz?"
"Ctg aqw ycvejkpi enqugna?"
"Duh brx zdwfklqj forvhob?"
"Evi csy aexglmrk gpswipc?"
"Fwj dtz bfyhmnsl hqtxjqd?"
"Gxk eua cgzinotm iruykre?"
"Hyl fvb dhajopun jsvzlsf?"
"Izm gwc eibkpqvo ktwamtg?"
Note: This program can be used for both ciphering and deciphering..!

2 comments:

Anonymous said...

Interesting code :)

Jithu Sunny said...

:)