DEV Community

Cover image for What I learned today?: Caesar cipher
cosckoya
cosckoya

Posted on

What I learned today?: Caesar cipher

Here I am studying Python and Cryptography at the same time. Just for fun. Oh! lucky man.

So, yesterday I was reading about famous cryptography methods along history, what were the purposes and how they changed in the modern times. Some of them, where really basic... but you know what they say "When a puzzle is solved is easy to understand".

So I was reading about Julius Caesar and it's crypto method for personal correspondency. (Did you know about it? Because I dont.)

This method is really simple, and it's based in a substitution type. In this case every character in the aplhabet gets a number from 0 to 25: A=0, B=1, C=2... Z=25.

Now you get a number between 0 and 25, that will be named as "key" and get a message to ecnrypt: I will use number 7 as a "key" and this message: "These Romans are crazy!" (yes, it's from Asterix comics). So...

Here we go:

Key: 7
Raw: "These Romans are crazy!"
Enc: "AOLZL YVTHUZ HYL JYHGF!"
Enter fullscreen mode Exit fullscreen mode

This means that T=A and Z=G. the "original" alphabet was "moved" 7 positions backwards:

Plain 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
Cipher T U V W X Y Z A B C D E F G H I J K L M N O P Q R S

With this script you can test this to encrypt:

#!/usr/bin/env python3

message = "Klaatu Barada Nitko."
key = 7
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

mode = "encrypt"  # set to 'encrypt' or 'decrypt'
translated = ""
message = message.upper()
# run the encryption/decryption code on each symbol in the message string
for symbol in message:
    if symbol in LETTERS:
        num = LETTERS.find(symbol)  # get the number of the symbol
        if mode == "encrypt":
            num = num + key
        elif mode == "decrypt":
            num = num - key

        if num >= len(LETTERS):
            num = num - len(LETTERS)
        elif num < 0:
            num = num + len(LETTERS)
        translated = translated + LETTERS[num]
    else:
        translated = translated + symbol

print(translated)
Enter fullscreen mode Exit fullscreen mode

And this othe one to decrypt:

#!/usr/bin/env python3

message = "RSHHAB IHYHKH UPARV!"
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

for key in range(len(LETTERS)):
    translated = ""
    for symbol in message:
        if symbol in LETTERS:
            num = LETTERS.find(symbol)
            num = num - key
            if num < 0:
                num = num + len(LETTERS)
            translated = translated + LETTERS[num]
        else:
            translated = translated + symbol

    print("Key #%s: %s" % (key, translated))
Enter fullscreen mode Exit fullscreen mode

You can find these scripts and more useful info in this book:

Title: Hacking Secret Ciphers with Python
Author: Al Sweigart
ISBN: 978-1482614374
Enter fullscreen mode Exit fullscreen mode

Have fun!

Discussion (0)