Sunday 17 May 2015

Caesar Cipher | Python 3.4.3

I've been looking into basic ciphers and cryptography lately and thought I would try to code some of them in python 3.4.3.

So here we have the Caesar Cipher, one of the earliest ciphers which we know for sure was used for keeping messages secret. It is a simple concept with person_1 writing a message they want to deliver to person_2, person_1 picking a random number (I have called this the displacement number), adding that number to the values of each letter in their message to person_2 to generate a new number (e.g. a=0, b=1 --> displacement_number = 3 --> a=0+3, b=1+3 --> a=3=c, b=4=d| ab --> cd) and therefore generating a seemingly random set of characters, and then passing on this random looking message with the displacement number on the end to person_2. Then all person_2 has to do to get the message is reverse engineer the message using the displacement number, and their message has been safely delivered!

The code overall if fairly simple only taking up 41 lines! More Cipher programs to come in following weeks! Any questions, I am more than happy to reply

The link for the python 3.4.3 code is here:

http://tinyurl.com/l7homd6

and the plain text code is here:

import math
import time

encrypt_letter_to_num = {"a":0,"b":1,"c":2,"d":3,"e":4,"f":5,"g":6,"h":7,"i":8,"j":9,"k":10,"l":11,"m":12,"n":13,"o":14,"p":15,"q":16,"r":17,"s":18,"t":19,"u":20,"v":21,"w":22,"x":23,"y":24,"z":25,"'":26,",":27,".":28,"?":29,"/":30," ":31}
encrypt_num_to_letter = {0:"a",1:"b",2:"c",3:"d",4:"e",5:"f",6:"g",7:"h",8:"i",9:"j",10:"k",11:"l",12:"m",13:"n",14:"o",15:"p",16:"q",17:"r",18:"s",19:"t",20:"u",21:"v",22:"w",23:"x",24:"y",25:"z",26:"'",27:",",28:".",29:"?",30:"/",31:" "}

while True:
    en_de = ""
    en_de = input("Would you like to encrypt a message or decrypt a message?[e/d]: ").lower()
   
    if en_de == "e":
        displace_num = int(input("Please enter your displacement: "))
        main_body = (input("Please input your message, all cases will be changed to lower: ")).lower()

        new_word = ""

        for x in main_body:
            old_value = encrypt_letter_to_num[x]
            new_value = old_value + displace_num
            while new_value > 31:
                new_value -= 32
            new_word += encrypt_num_to_letter[new_value]

        print(new_word)



    if en_de == "d":
        displace_num = int(input("Please enter your displacement: "))
        main_body = (input("Please input your message as it was sent: ")).lower()

        new_word = ""

        for x in main_body:
            old_value = encrypt_letter_to_num[x]
            new_value = old_value - displace_num
            while new_value < 0:
                new_value += 32
            new_word += encrypt_num_to_letter[new_value]

        print(new_word)

No comments:

Post a Comment