Implementing the caesar cipher in python and in turn, the ROT13 cipher.

0. Prerequisites

Caesar Cipher

Basic Python

1. A Recap

In the last post we devloped a method to encipher a single character with the caesar cipher. Now we’ll implement a full program that enciphers a whole block of text.

Remember functions from the last post ? This time we’ll create our own function. So lets get started.

2. The def keyword

In python, function are defined using the def keyword.

def <func-name> (<params>) :
  <body-of-function>
  [return <value>]

for example if we want to define a function add that takes two values and returns their sum the we would say

def add(a,b):
  c = a+b
  return c
print 'sum of 1 and 2 is ' + sum(1,2)

This will print sum of 1 and 2 is 3

Note how change in indentation(spaces, that is) is used to denote the start and end of the function. You can indent with any number of space or tabs but you should be consistent with it. Never mix tabs and spaces.

3. Making modules

Most of the work we did was on the python interpreter. While it is really useful to test new features, it has a serious drawback : If you quit from the Python interpreter and enter it again, the definitions you have made (functions and variables) are lost. That is terribly inconvenient. So python provides a way for you to store the definitions and commands in a file and load that file when required. Such a file is called a script or a Python Module.

Now you can reuse your code !

To make a module simple open up your favourite code-editor ( not a text-editor like notepad but like sublime-text or emacs ) , type your commands and save it as file with suffix .py.

You can now execute it in the terminal as many times as you like.

4. The first function

Now, simply type all the code from the last post to a function named encipher(c, shift)

Your file should look something like this :

def encipher(letter,shift):
  letter = letter.upper() # just to make sure the letter is uppercase
  ascii_letter = ord(letter)
  ascii_A = ord('A')
  pos_letter = ascii_letter - ascii_A
  shifted_pos_letter = ( pos_letter + shift )%26
  asc_ciphered_letter = shifted_pos_letter + ascii_A
  return chr(asc_ciphered_letter)

Go ahead and save the file in your home directory ( or, C:\python27 for windows users) as cipher.py.

Now open a terminal and type

>>> import cipher
>>> cipher.encipher('A',2)

In the next line you will get

'C'

To get back your original text you will have to shift back

That is

>>> cipher.encipher('C',-2)
'A'

Here, in the first line you are loading the file into the interpreter and in the second, you are calling the function named encipher from the module cipher with parameters ‘A’ and 2. That is, ‘A’ will be shifted by 2 places.

5. Enciphering a block of text

So we can encrypt and decrypt single characters but what if we have to encrypt a whole block of text or a sentences. To avoid writing all the calls to the function or to repeat anything python provides the for loop which simply means repeat a particular task certain number of times. Basically this

for i in range(100):
  print 'I will follow the rules.'

instead of this

images

So this is what our second function looks like now

def encipher_text(text,shift):
  ciphertext = ''
  for c in text:
    ciphertext += encipher(c,shift)
  return ciphertext

It calls the encipher function for **each **of the characters of text. But not all characters are letters of the alphabet. They may be white-space like a tab or a space or the may be special characters or numbers. We don’t want to shift them. So we’ll check each character if it belongs to the alphabet before calling the encipher function

def encipher_text(text,shift):
  ciphertext = ''
  for c in text:
      if c.isalpha():
          ciphertext += encipher(c,shift)
      else :
          ciphertext += c
  return ciphertext

Now just like in section 4 you can try to encipher a sentence or a block of text.

>>> cipher.encipher_text("This is how you encrypt a sentence.",10)
'DRSC SC RYG IYE OXMBIZD K COXDOXMO.'

6. ROT13

ROT13 is a special case of the caesar shift. As the name implies it shifts the text by 13 places so if we encrypt it again we get the original text.

This type of encryption is used in online forums as a means of hiding spoilers, punchlines, puzzle solutions, and offensive materials from the casual glance. It has been described as the “Usenet equivalent of a magazine printing the answer to a quiz upside down”.

We can write rot13 as a special case of out encipher_text function

def rot13(text):
    return encipher_text(text,13)

7. The code

View the whole code(Hosted by github)

An Introduction to Cryptography and developing a very basic algorithm for the Caesar Cipher - A precursor to the Vigenère Square and ROT13 Encryption methods.

0. Prerequisites

Basic knowledge of Python syntax and constructs.

1. Cryptography

Cryptography is the science of writing in secret code. It comprises of Encryption (that is, changing data so that it is unrecognisable and useless to an unauthorised person) and Decryption (that is, changing it back to its original form.)

crypto

(source:http://www.cryptographyworld.com/ )

2. The need for Cryptography

> > _ For thousands of years kings, queens and generals have relied on efficient communication in order to govern their countries and command their armies. At the same time, they have all been aware of the consequences of their messages falling into the wrong hands, revealing precious secrets to rival nations and betraying vital information to opposing forces._ > > > > _It was the threat of enemy interception motivated the development of codes and ciphers: techniques for disguising a message so that only the intended recipient can read it._" > > > > Simon Singh > > > > "The Code Book > >

These few lines accurately sum up the necessity of codes and ciphers.

In modern context, the ability to protect and secure information is vital to the growth of electronic commerce and to the growth of the Internet itself. Many people need or want to use communications and data security in different areas.

  • Banks use encryption methods all around the world to process financial transactions. These involve transfer of huge amount of money from one bank to another.

  • The average internet user relies on cryptography not only to protect his passwords and other private data but also to verify his identity ( The RSA Encryption ).

  • Multinational firms may use it to protect their trade secrets.

3. Types of Cryptography

There are mainly three ways of encryption (that is scrambling up a message so that it may only be read by its intended recipient) :

crypto_types(source: http://www.garykessler.net/library/crypto.htm)

4. The Caesar Cipher

Caesar Cipher is a simple case of the Symmetric Key Cryptography. It is a substitution cipher(that is, each letter is replaced by another letter or symbol) named after Julius Caesar.

Although easily crackable with modern technology, it is still used in the form of ROT13 ( a caesar shift of 13 places ) in certain forums to hide offensive text or answers to a quiz.

Each letter in the plaintext message is replaced by the letter k places along in the alphabet (where k is between 0 and 25 inclusive) wrapping around to the beginning of the alphabet if necessary.

If k be 3, then A is replaced by D, B is replaced by E, C is replaced by F and so on.

caesar-cipher

The Caesar Cipher using a shift of k=3.

To decrypt (or, decode) such a coded message, each letter is replaced by the letter k places before it in the alphabet, wrapping around to the end if necessary.

That is, for our example of wrapping around to thek=3, A is replaced by X, B is replaced by Y, C is replaced by Z, D is replaced by A and so on.

5. A Math Primer

Because cryptography is basically an application of math and, ( more recently ) programming, there are certain mathematical concepts that I would like you to be familiar with ( Don’t worry - it won’t be like a boring math class and I’ll keep it as simple as possible )

5.1 The Modulo Operator

In Python, the ‘%’ is the modulo operator. It finds the remainder of division of one number by another. For example, 9 % 5 means, divide 10 by 5 and return the remainder of the division ( as opposed to the ‘/’ which returns the quotient of the division ). So 9 % 5 will be 4.

Go ahead and try this out in the python interpreter ( simply type 9%5 and press enter )

Remember I said we’ll have to wrap around the alphabet ? The modulo operator can be used for just that ( the value of a%b will always be less than b )

5.2 ASCII Values

Not exactly math but the American Standard Code for Information Exchange encodes 128 characters into 7-bit integers.

The ASCII Table http://ascii.cl/

5.3 Functions

A function simply relates an input to an output.

Each function has three main parts:

1.The Input

2.The Relationship

3.The Output

Screenshot from 2014-10-20 14:15:28

(source: http://www.mathsisfun.com/sets/function.html)

If we write it a bit more formally, the function will be

f(x) = x*2

In programming, functions are “self-contained” modules of instructions that accomplish a specific task. Functions usually “take in” data, process it, and “return” a result.

Python has many functions in its standard library ( that is, they are built-in ). So, for time being, we don’t need to care about how the relationship is established ( or, how a task is done ). For example if we want to get the user’s name, we’ll use the raw_input function -

name = raw_input('What is your name? ')

You may try this out in the python interpreter.

name is a variable that stores the return value or output of the raw_input function

‘What is your name? ‘ is a string that is displayed on the screen to prompt the user. It is a parameter or the input to the function.

Some more useful functions are as follows :

  • ord(c) : returns the ASCII value of a character c ( that is, a string of length one in python like ‘a’ and ‘b’ )

https://docs.python.org/2/library/functions.html#ord

  • chr(i) : returns the character corresponding to the ASCII value

https://docs.python.org/2/library/functions.html#chr

  • int(s) : returns an integer constructed from the string/int/float value s

https://docs.python.org/2/library/functions.html#int

  • range(start,stop[,step]) : returns a list of integers from start to stop-1 at a gap of step. Only stop is mandatory, rest are optional. For example,

    range(5)

will return

[0, 1, 2, 3, 4]

https://docs.python.org/2/library/functions.html#range

6. A To-Do list

When you get down to it, programming is all about algorithms. That’s a big fancy word for ‘a list of instructions.’ Every program is simply a big to-do list of instructions for the computer to follow. So, we’ll first try to write down the steps involved in encrypting a single uppercase letter with the caesar cipher.

  • Let the letter be ‘plain_letter’, its ASCII value be ‘asc_letter’, and the shift be ‘k’

  •  Calculate its position in the alphabet ( A=0, B=1, C=2 and so on )

    pos_letter = asc_letter – ASCII_Value_of_A

  • Shift it by k places wrapping around the alphabet.

    shifted_position_of_letter = ( pos_letter + k ) % 26

  • Get the ASCII value from the shifted position value and then get the ciphered character corresponding to the ASCII value

    asc_ciphered_letter = shifted_position_of_letter + ASCII_Value_of_A

 For example, let’s shift ‘C’ by 5 places

* ASCII Value of C = 67


* ASCII Value of A = 65


* Position of C = 67- 65 = 2


* Shifted position of C = (2+5) %26 = 7%26 = 7


* ASCII Value of Shifted C = 7 + 65 = 72


* Character corresponding to ASCII Code (72) = 'H'

C D E F G H

Hence, C has been shifted 5 places.

7. Implementation in python

You may now fire up your interpreter and use the functions to implement the algorithm on your own. A more detailed implementation and cracking the Caesar Cipher will be in the next post.