Skip to content

Python: Cryptography Caesar shift encryption (shift cipher)

by mat on December 21st, 2009

I have always had a keen interest in cryptography and rather than give a brief history of cryptography I will recommend reading Simon Singh’s The code book or for a modern and hands on approach Applied Cryptography by Bruce Schneier (Who also made a brilliant book on security, more of descriptive approach but very interesting Secrets and Lies: Digital Security in a Networked World).

This post aims to detail the creation (in python) of one of the simplest forms of encryption; the simple Caesar shift (or shift cipher). The Caesar shift takes the normal alphabet and maps it to a an identical alphabet with a rotation. The cipher will be written in such a way that it can be easily expanded on to create more complex encryption schemes with little modification.

Caesar shift alphabet

Caesar shift alphabet diagram

The above image shows a diagrammatic representation of a Caesar shift of 3 (alphabet transposed onto a rotation of itself with a displacement of 3). Below shows the entire alphabet in plaintext and in ciphertext, followed by a simple sentence in plaintext and in cipher text.

Plaintext: abcdefghijklmnopqrstuvwxyz
Ciphertext: defghijklmnopqrstuvwxyzabc
Plaintext: the cat sat on the mat
Ciphertext: wkh fdw vdw rq wkh pdw

Below is the code to convert plaintext into ciphertext along with an example of the usage:

def caesar(plaintext,shift):

	alphabet=["a","b","c","d","e","f","g","h","i","j","k","l",
	"m","n","o","p","q","r","s","t","u","v","w","x","y","z"]

	#Create our substitution dictionary
	dic={}
	for i in range(0,len(alphabet)):
		dic[alphabet[i]]=alphabet[(i+shift)%len(alphabet)]

	#Convert each letter of plaintext to the corrsponding
	#encrypted letter in our dictionary creating the cryptext
	ciphertext=""
	for l in plaintext.lower():
		if l in dic:
			l=dic[l]
		ciphertext+=l

	return ciphertext

#Example useage
plaintext="the cat sat on the mat"
print "Plaintext:", plaintext
print "Cipertext:",caesar(plaintext,3)
#This will result in:
#Plaintext: the cat sat on the mat
#Cipertext: wkh fdw vdw rq wkh pdw

Explanation
Here we have written a function that is given the plaintext and an arbitary rotation (including negative) and returns a ciphertext. The function creates a dictionary, mapping each letter to another letter that is ‘shift’ letters away from it in the alphabet (the modulus (%) is used so to wrap the alphabet back to the start if it falls off the end). It then converts each letter of the plain text into the corresponding encrypted letter using the dictionary.

Future
In the next post I will discuss methods to improve the Caesar shift and how to turn it into a full substitution cipher (where the alphabet is shuffled rather than rotated). The Caesar shift is very susceptible to brute forcing and frequency analysis which I shall explain and create a program to defeat these encryptions in a future post.

10 Comments
  1. Hi !
    Your code is very clean, but i don’t understand line 9 : what’s “shift” ? You didn’t create any variable named after this …

    Instead of a dictionnary, you could have used a string in order to run the string.translate() method instead of lines 13-17.

    I made a caesar decoder, which use a dictionnary of words to decode :

    #!/usr/bin/env python
    import string       
    
    def decode (n, text):
    
             #First, we build the coded-alphabet for n substitutions
    	alphabet= 'abcdefghijklmnopqrstuvwzyz'
    	alphabet_code = ''"
    	for x in range (0, len(alphabet)):
    		d = 0
    		for y in range (0, n+1):
    			if x+y -d > 25:
    				x=0
    				d = y
    			letter=alphabet[x +y -d]
    			y += 1
    		alphabet_code += letter
    		x += 1
    
    	table = string.maketrans(alphbet_code , alphabet) #Decoding
    	
            #Then, by checking every decoded word with a dictionnary, we check if the decoded string is the right
    	decode=text.translate(table)
    	file=open('dictionnary.txt' , 'r')
    	words= file.readlines()
    	good=0
    	for x in words:
    		if x[0:-1] in decode and len(x) > 3:
    			good += 1
    	if bon > 1:
    		print decode
    	file.close()
    
    if __name__ == '__main__':
    	text = raw_input('Enter the Caesar message to decode').lower()
    	for z in range (1, 27):
    		decode ( z , text)
    		z += 1
    
  2. All substitution ciphers are easily expressed with Python’s str.translate or unicode.translate that basically work with explicit subsitutions.

    See http://stackoverflow.com/questions/1538935/caesars-cipher-using-python-could-use-a-little-help/1539611#1539611

  3. @wumzi: shift is passed to the function caesar(plaintext,shift) and defines how far the transposed alphabet is moved. IE shift=0 a=a b=b, shift=1 a=b b=c etc…. Also thanks for your code, I’ll give it a try after I write my own version :)

    @Ulrik: Cheers for the link, that looks like a simpler solution however I don’t think it could be used for the customizations that I’d like to include in future versions (such as methods for defeating frequency analysis)

  4. @mat:

    Sorry, there’s mistakes in the code, i just translated the names in english before posting it , and moreover there’s no indentation :)

    But, it’s now posted on my wiki : http://www.wumzi.info/wiki/doku.php?id=decodeur_de_code_cesar

    Yes, I’m from France

  5. Thanks wumzi, I’ve rewritten the caesar and substitution ciphers to use the maketrans function. The new functions can be found here

  6. It is indeed facilitation for our modern life in which we do not
    have time to install curtain rods after drilling in the walls and fixing accessories.
    Everything doesn’t have to match perfectly, in fact, it’s better if things don’t match perfectly as this provides ample opportunity to mix and match as your finalize your bathroom and make more expensive renovations and alterations later on. It is also quite easy to get a good deal at the right price by doing a little bit of background research.

  7. After exploring a few of the blog posts on your blog,
    I truly like your technique of writing a blog.
    I book marked it to my bookmark webpage list and will be checking back in the
    near future. Please check out my web site as well and
    let me know how you feel.

  8. It’s actually a nice and useful piece of info. I am satisfied that you simply shared this helpful info with us. Please keep us up to date like this. Thanks for sharing.

  9. Schenken Sie Ihrem Kind einen Wald-Abenteuer-Geburtstag!Anmeldeschluss: 10 Tage vor
    Veranstaltungsbeginn. An Aktionstischen können Besucher
    eigene Beobachtungen machen und experimentieren. Kosten bei 6 bis
    9 Kindern: 6 Kinder für 115 € / jedes weitere Kind 8 € / jeder
    weitere Erwachsene 15 € Kosten bei 10 bis 14 Kindern: 169 € pauschal (Kostenaufwand für zweiten
    Trainer) Kosten ab dem 15 Kind: jedes weitere Kind 8 € / jeder weitere
    Erwachsene 15 € Wenn der Outdoor-Hochseilgarten und Flying-Fox zugebucht werden soll,
    verlängert sich der Kindergeburtstag um eine halbe
    Stunde auf 3,5 Stunden gesamt.

Trackbacks & Pingbacks

  1. Learning by simulacron3 - Pearltrees

Leave a Reply

Note: I am currently writing my thesis so probably wont have time to reply to your comment
Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS