# Python: Cryptography Caesar shift encryption (shift cipher)

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 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.

1. wumzi

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')
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. Ulrik

All substitution ciphers are easily expressed with Python’s str.translate or unicode.translate that basically work with explicit subsitutions.

3. mat

@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. wumzi

@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. mat

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

6. Learning by simulacron3 - Pearltrees

[…] Python: Cryptography Caesar shift encryption (shift cipher) | Stealthcopter.com plaintext= "the cat sat on the mat" print "Plaintext:" , plaintext return ciphertext […]

7. Felix

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.

8. Kindergeburtstag Mannheim

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.

9. kindergeburtstag Mannheim

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.

#Defines the main function
def caesar(string, shift):

#Stores the alphabet, large and small
beta = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”
alpha = “abcdefghijklmnopqrstuvwxyz”

#result storage
result = []

#iterates through the string, checks if letter is in alpha or beta and appends shifted letter
for x in string:
if x in beta:
result.append(beta[(beta.index(x) + shift) % 26])
elif x in alpha:
result.append(alpha[(alpha.index(x) + shift) % 26])
else:
result.append(x)

#joins the result and returns it
result = “”.join(result)
return result

plaintext = “the cat sat on the mat”
print (“Plaintext: “, plaintext)
print (“Cipertext: “,caesar(plaintext,3))

11. .

the only one i can find on the internet that actually works

12. Siddharth

It was very useful to me keep on uploding this type of comes.

13. 95Rosemary

Hi admin, i must say you have high quality posts here.
Your page can go viral. You need initial traffic only. How to get it?

Search for; Mertiso’s tips go viral