How to Encrypt text with the Caesar cipher in Python

Introduction:

Text encryption is very popular among secret organizations, and hackers, while the sole purpose being to ensure a message sent is deciphered by the right party. In today’s tutorial we will be talking about, text encryption with the Caesar cipher using Python.


The Caesar cipher is probably among the oldest text encryption techniques out there. It is pretty to easy to use and somewhat hard to decipher (at least back then when there was no fast computers), it makes use of the cipher wheel, which is a wheel with the English alphabet inscribed on it from A-Z.

Cipher wheel used to encrypt text with Caesar cipher
cipher wheel used by Caesar cipher source:Hacking Secret Ciphers with Python By Al Sweigart

How it works:

Alphabets and number values
alphabets and number values source:Hacking Secret Ciphers with Python By Al Sweigart

Encrypting text:

To encrypt text with the Caesar cipher we follow this simple steps:.
Giving the text “Hello how are you”.

  • Choose a key within 0-25 this will be our secret key for both encrypting and deciphering our text/message keep it secret!.
  • Find the number value of each alphabet in our text (a is 0,b is 1……….z is 25).
  • add our secret key to each of our alphabet number values (7+key,4+key………….20+key).
  • Find the number values after addition,that are greater than 26 and subtract 26 from them.
  • Find the alphabet with the corresponding number value, after our math operation this is our cipher text.
  • Repeat step 2 – 5 until all our text have been encrypted.

The image below better explains the encryption techniques above:

Text encryption using Caesar cipher
encrypting cipher text source:Hacking Secret Ciphers with Python By Al Sweigart

Deciphering text:

To decipher a text, encrypted with the Caesar cipher, we follow this steps:.

  • Given a deciphering key x and a cipher text y.
  • Find the number values of our cipher text.
  • Subtract our cipher key x from the number values(n¹-x,n²-x,………nⁿ-x)
  • Find the number values after subtracting, that are less than 1, and add 26 to them.
  • Find the alphabet with the corresponding number value, after our math operation, this is our deciphered text.
  • Repeat step 2-5 until every text is deciphered.

The image below better explains our deciphering technique.:

Text decryption using the Caesar cipher
Decrypting cipher text Caesar cipher source:Hacking Secret Ciphers with Python By Al Sweigart

The python code:

Handling text encryption and decryption with the Caesar cipher using Python.

from string import ascii_lowercase #imports strings of aphabet


def return_alpha_index(a):
    """ returns the index of an alphabet """
    alphabets = ascii_lowercase
    for i,j in enumerate(alphabets):
       if j == a:
           return(i)
    return(a)

def return_index_alpha(n):
    """ returns an alphabet given the index"""
    alphabets = ascii_lowercase
    for i,j in enumerate(alphabets):
       if i == n:
           return(j)
    return(n)


def encryption(text,key=13):
    encryption,result = [],[]
    #get the index of the alphabets in text and add the key to them
    for i in text:
        try:
            encryption.append(return_alpha_index(i)+key)
        except:
            encryption.append(return_alpha_index(i))
    #check if a number value is greater than six then subtracts 26 from it 
    for i in encryption:
        try:
            if i >= 26:
                result.append(i-26)
            else:
                result.append(i)
        except:
            result.append(i)
    #get the new number values which is our cipher text
    encryption = "".join([return_index_alpha(n) for n in result])
    return(encryption)


def decryption(text,key=13):
    encryption,result = [],[]
    #get the index of the alphabets in text and subtract the key from them
    for i in text:
        try:
            encryption.append(return_alpha_index(i)-key)
        except:
            encryption.append(return_alpha_index(i))
    #check if a number value is less than 0 then add 26 to it 
    for i in encryption:
        try:
            if i < 0:
                result.append(i+26)
            else:
                result.append(i)
        except:
            result.append(i)
    #get the new number values which is our cipher text
    encryption = "".join([return_index_alpha(n) for n in result])
    return(encryption)


key = 13
text = "Hello this is an encrypted message"
encrypt = encryption(text,key=key)
decrypt = decryption(encrypt,key=key)


print("Text :%s"%text)
print("encrypt :%s"%encrypt)
print("decryption :%s"%decrypt)
    
    
        

Program execution:

Text encryption with the Caesar cipher using Python
Encrypt and decrypt using Caesar cipher in Python

Conclusion:

Although the Caesar cipher is elegant in it’s own way, it is not secure though you can still add encryption for special characters to make the cipher a little bit harder to crack.
You can check out the code on my GitHub repo . Please do share to your friends and share your thoughts in the comment section

13 comments

  1. Wow that was odd. I just wrote an incredibly long comment but after I clicked submit my comment didn’t show up. Grrrr… well I’m not writing all that over again. Anyways, just wanted to say fantastic blog!

  2. I have to thank you for the efforts you’ve put in writing this site. I really hope to view the same high-grade blog posts by you later on as well. In truth, your creative writing abilities has inspired me to get my very own website now 😉

  3. Right here is the right blog for anyone who wishes to find out about this topic. You know so much its almost tough to argue with you (not that I really would want to…HaHa). You definitely put a brand new spin on a subject that has been written about for a long time. Excellent stuff, just excellent!

  4. Pingback: My Homepage
  5. Wow, ѕuρerb blog layout! How long have you been blogging
    for? you made blogging look easy. The overall looк of yoսr site is wonderfuⅼ, as well as the content!

  6. Hellο tһere, There’s no doսbt that yoᥙr site could posѕibly Ƅe having internet browser compatibility issues.
    Whenever I take a look at your blog in Safari, it lookѕ fine however, іf opening in I.E.,
    it’s got some overlapping issues. I merely wanted
    to provide you with a quick һeadѕ up! Aside from that, great
    weƄsite!

  7. Heʏ There. I discovered your blog using msn. This is a realⅼy welⅼ ᴡrіttеn article.

    I will be sure to bookmark it and come back to гead extra ߋf
    your useful info. Tһanks for the post.
    I will certainly return.

Leave a Reply

Your email address will not be published. Required fields are marked *