•

Check out our Community Blogs

Register and join over 40,000 other developers!

### Recent Blog Entries

• phi

I love this community !

• JackJames

hi i am jack i am seo expert jack james would love you to read new post

# [cryptography / python] Caesar Shift encryption

encryption

15 replies to this topic

### #1 Hignar

Hignar

• 239 posts

Posted 18 July 2009 - 12:05 PM

I've been reading a book about cryptography recently. The book in question is "The Code Book - A Secret History of Codes and Code-Breaking" by Simon Singh (Amazon link). While there is no programming content in the book it covers the ideas needed to be able to come up with your own programs.

Unfortunately, there isn't a lot of 'heavy' programming needed to encrypt and decrypt messages using simple methods. Code-breaking is where the serious programming comes into play. I hope to cover code-breaking in a tutorial in a little while!

The first type of encryption that is covered in the book is known as a Caesar shift (so called due to its use by Julius Caesar).

The Caesar shift is a substitute cypher where each letter in a message is replaced with a letter a predetermined number of steps down the alphabet.

For example if we use a shift of 3 we get the following substitutions

```Plain: 	abcdefghijklmnopqrstuvwxyz
Cipher:	defghijklmnopqrstuvwxyzabc
```

Thus the message "this is a message" would be translated to "wklv lv d phvvdjh".

In order to write a program that will encrypt a message we have to first produce the cipher alphabet based on the desired number of steps.

```stdalph = ['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']
crypalph = []
```

After asking the user to enter the desired number of steps we can fill the cipher alphabet using modular arithmetic. Assuming a shift of 3, we want the first entry of crypalph to be 'd', the second to be 'e' and so on until we have crypalph[25] = c.

```shift = 3
for x in range(0,26):
crypalph.append(stdalph[(x+shift)%26])
```

Now, given a message (either entered by the user or read from a file), we need to substitute each letter in the message with the corresponding letter from the cipher alphabet. This method of encryption only substitute the letters in the message (although it can clearly be extended to cover punctuation marks and white space) so we need to decide what to do with punctuation etc. One answer is to simply leave the punctuation in place. This method is the least secure as the punctuation marks could give anyone who intercepts the message additional clues to help crack the code. The second option is to remove all punctuation and white space.

Although the second method is more secure I have opted to use the first method as it allows me to use a nice feature of python. In order to determine whether or not to substitute an individual character we need to know if it's a letter of the alphabet or not. Thus all we have to do is see if each character is in stdalph. As python evaluates all none zero integers as true and zero as false we can use the count() function to return the number of times a character is in stdalph i.e. 1 for a letter of the alphabet and 0 for any other punctuation etc.

So the encrypt the message all we have to do is loop through the message a character at a time and make the substitution where necessary.

```message = 'this is a message'
cryptmessage =''

for x in message:
if stdalph.count(x):
cryptmessage += crypalph[stdalph.index(x.lower())]
else:
cryptmessage += x

print cryptmessage
```

gives the output:

```wklv lv d phvvdjh
```

Due to the simple nature of the encryption, decryption works in exactly the same way.

```cryptmessage ='wklv lv d phvvdjh'
message = ''

for x in cryptmessage:
if stdalph.count(x):
message += stdalph[crypalph.index(x)]
else:
message += x

print message
```

Giving the output
```this is a message
```

Unfortunately the Caesar shift isn't a very secure method of encryption. With only 26 possible cipher alphabets (one of which is just the standard alphabet) it wouldn't take very long for someone to try each possible shift value and decipher the message. The strength of the cipher can be improved by the use of a keyword. Using the keyword "Codecall" we can produce a cipher alphabet as follows:

1) Remove duplicate letters from the keyword giving us "codeal"
2) Place the new keyword at the start of the cipher alphabet
3) Fill the remainder of the cipher alphabet with the letters of the alphabet in order starting with the letter after the last letter of the keyword, excluding those used in the keyword.

Thus, the cipher alphabet for the keyword "codecall" would be

```Plain: 	abcdefghijklmnopqrstuvwxyz
Cipher:	codealmnpqrstuvwxyzbfghijk
```

Given the vast number of possible keywords or keyphrases that could be used a brute force attack on the encrypted message would take much longer than if a simple Caesar shift was used.

I hope to produce a further tutorial on the use of keywords and using cryptanalysis to break codes when the keyword or phrase isn't known.
• 5

### #2 WingedPanther73

WingedPanther73

A spammer's worst nightmare

• Moderator
• 17757 posts
• Location:Upstate, South Carolina
• Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
• Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others

Posted 18 July 2009 - 01:11 PM

Nice intro to encryption
• 0

Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

My MineCraft server site: http://banishedwings.enjin.com/

### #3 Guest_Jordan_*

Guest_Jordan_*
• Guest

Posted 20 July 2009 - 04:26 AM

Very cool Encryption article. +rep!
• 0

### #4 Brandon W

Brandon W

CC Mentor

• Expert Member
• 2092 posts
• Location:Ipswich, Australia
• Programming Language:C, Java
• Learning:Java, C++, JavaScript

Posted 21 July 2009 - 10:26 PM

This is a simple method of encryption and you done a great job of explaining it mate. Well done, I will look forward to your tutorial on code-breaking.

Will it be written in Python too?

EDIT: Forgot +rep
• 0
I've returned...

### #5 OrlandoBlue

OrlandoBlue

CC Lurker

• Just Joined
• 1 posts

Posted 20 August 2009 - 09:47 AM

Nice work man!!!
keep that way, i'll be looking for your tutorial.
• 0

### #6 dargueta

dargueta

I chown trolls.

• Moderator
• 4854 posts
• Programming Language:C, Java, C++, PHP, Python, JavaScript, Perl, Assembly, Bash, Others
• Learning:Objective-C

Posted 20 August 2009 - 12:18 PM

I have the book you mentioned - fantastic read. I actually wrote a Vigenere cipher program last week...maybe I'll post it as an addendum to your series (not to steal your thunder, Hignar). It's in C, though.
• 0

sudo rm -rf / && echo \$'Sanitize your inputs!'

### #7 Hignar

Hignar

• 239 posts

Posted 20 August 2009 - 11:29 PM

I have the book you mentioned - fantastic read. I actually wrote a Vigenere cipher program last week...maybe I'll post it as an addendum to your series (not to steal your thunder, Hignar). It's in C, though.

Don't worry about stealing my thunder, I really don't think there's all that much to steal. Besides I'd love to see your code.

For those who've expressed interest in the follow up I promised, it is coming. I've been very busy at work and I've decided to drop both python and C# for the moment to learn C++. If I can find time this weekend I may try getting back into it by rewriting this in C++.
• 0
If there's a new way, I'll be the first in line.

But, it better work this time.

### #8 emmaright

emmaright

CC Lurker

• New Member
• 5 posts
• Programming Language:PHP, (Visual) Basic, Others
• Learning:Python

Posted 28 January 2013 - 04:13 PM

Can anybody please explain what the %26 means or does at the end of this line:

crypalph.append(stdalph[(x+shift)%26])
• 0

### #9 dargueta

dargueta

I chown trolls.

• Moderator
• 4854 posts
• Programming Language:C, Java, C++, PHP, Python, JavaScript, Perl, Assembly, Bash, Others
• Learning:Objective-C

Posted 28 January 2013 - 05:05 PM

That's the modulus operator, which simply divides the left side by the right and returns the remainder. For example:

2 doesn't divide evenly into 5...
5 % 2 = 1
5 / 2 = 2.5

...but it divides 6 just fine.
6 % 2 = 0
6 / 2 = 3

You don't always get 1 or 0 though.
100 % 26 = 22
100 / 26 = 3.846...

Edited by dargueta, 28 January 2013 - 05:05 PM.

• 1

sudo rm -rf / && echo \$'Sanitize your inputs!'

### #10 emmaright

emmaright

CC Lurker

• New Member
• 5 posts
• Programming Language:PHP, (Visual) Basic, Others
• Learning:Python

Posted 29 January 2013 - 10:08 AM

Thank you for the quick response. I understand it now
• 0

### #11 MindiAbair

MindiAbair

CC Lurker

• New Member
• 3 posts

Posted 12 September 2013 - 02:34 AM

Self-study learner here and read this with great interest.

I have an idea for a different encryption method but don't know what it's called. Basically, it involves multiplying the ASCII value of each message character by an integer from 2 to 9, except the integer is chosen randomly at time of encryption and written in a key. Legitimate decryption would involve using the key, and cracking would involve dividing the ASCII value of each character in the encrypted message by values ranging from 2 to 9 until you ended up with the right message.

This is a quick and dirty look at how the code might look:

```#! /usr/bin/env python3

from random import randint

output_phrase = ""
encryption_key = []

input_phrase = input("Type something to encrypt: ")

for x in input_phrase:
encryption_value = randint(2,9)
output_character = asc(input_phrase) * encryption_value
output_phrase + output_character
encryption_key.append(encryption_value)

# then do whatever with the enrypted phrase and encryption key
```

As I said, I don't know what this encryption method is called, but it seems to be straightforward enough. What do you think?

• 0

### #12 gonerogue

gonerogue

• 197 posts

Posted 12 September 2013 - 02:45 AM

Your key will be as long as the message to be encrypted, right ?

Edited by xyv123, 12 September 2013 - 02:46 AM.

• 0

### Also tagged with one or more of these keywords: encryption

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download