DEV Community

Leroy Leow
Leroy Leow

Posted on

Crack the Code Like Caesar: Build Your Own Secret Message Encrypter! [Python code included]

Image description

The Caesar cipher, also known as the Caesar shift or Caesar’s code, is one of the oldest and simplest encryption techniques in the history of cryptography. It is named after Julius Caesar, the Roman military general and statesman who is believed to have used this method for secure communication with his officials around 58–51 BC. Julius Caesar employed this cipher to protect the confidentiality of his military orders and messages, allowing him to communicate sensitive information without being easily understood by adversaries.

How It Works

The Caesar cipher is a substitution cipher. It involves shifting each letter in the plaintext by a fixed number of positions down or up the alphabet. This shift is known as the key. The original Caesar cipher uses a fixed shift of 3 positions down the alphabet. For example:

A becomes D
B becomes E
Z becomes C (wrapping around the alphabet)

While the Caesar cipher provided a basic level of security for its time, it is relatively simple to break. With only 26 possible keys to try (since the key can be between 0 and 25), a brute-force attack can quickly reveal the plaintext.

Implementing the Caesar Cipher in Python

Let’s write a simple Python program to encrypt and decrypt messages using the Caesar cipher. In this example i will assume to hardcode the alphabets and special characters in SYMBOLS variable.

#caesarCipherv1 take both plaintext and key as input to create a ciphertext

inputtext = input("What is input plaintext:")
key = int(input("What is the caesar key:"))     #try to convert string to
mode = input("encrypt/decrypt:")

# Every possible symbol that can encrypted
SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcedfghijklmnopqrstuvwxyz!@#$%^&*()_+0123456789'

outtext = ""

for character in inputtext: 
    if character in SYMBOLS:
        #replace character by the key position
        if mode == 'encrypt':
            index = SYMBOLS.find(character) + key
        elif mode == 'decrypt':
            index = SYMBOLS.find(character) - key

        #print("the %s" % (index))

        if index >= len(SYMBOLS):
            index = index - len(SYMBOLS)
        elif index < 0:
            index = index + len(SYMBOLS)

        outtext = outtext + SYMBOLS[index]
    else:
        outtext = outtext + character

print(outtext)
Enter fullscreen mode Exit fullscreen mode

While the program works well, there are a couple of areas for improvement:

  1. Key Value Limitation: Currently, the key value is limited by the length of the SYMBOL variable. In fact, it can only be up to twice the length of SYMBOL.
  2. Hardcoded Symbols: The SYMBOLS variable is currently hardcoded. This means it’s not very flexible if you want to use a different character set in the future. We can address these limitations in below to make the program even more versatile!
import sys
from colorama  import Fore, init

def caesar_cipher(text, key):
    result = ""
    for character in text:
        #print("%s" % (ord(character)))
        if character.isupper():
            #upper character
            result += chr((ord(character) - 65 + key) % 26 + 65)
        elif character.islower():
            #lower character
            result += chr((ord(character) - 97 + key) % 26 + 97)
        elif ord(character) in range(33, 57):
            #special character
            result += chr((ord(character) - 33 + key) % 25 + 33)
        else:
            #not found cant encrypt
            result += character
    return result

def main():
    try:
        # Get user input
        text = input("Enter the text to encrypt or decrypt:")
        key = int(input("Enter the key value(positive for encryption, negative for decryption):"))

        #caesar function
        cipher_text = caesar_cipher(text, key)

        #print the result
        print(f"{Fore.GREEN}Result:{Fore.RESET} {cipher_text}")
    except ValueError:
        print(f"{Fore.RED}Error:{Fore.RESET} Invalid input. Please enter a valid key value (integer)")

if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

The caesar_cipher function effectively implements the Caesar cipher algorithm. It takes the plain text message and a key value (positive for encryption, negative for decryption) as input.

Here’s a breakdown of its functionality:

  1. Character Processing: It iterates through each character in the message.
  2. ASCII Conversion: It leverages the built-in ord function to determine the numerical representation (ASCII value) of each character.
  3. Shifting and Wrapping: Based on the character case (uppercase or lowercase) and the key value, it performs the Caesar shift. The function ensures the shift stays within the alphabetical boundaries by using a modulo operation (%). This ensures the encryption 'wraps around' if the shift goes beyond the alphabet's end.
  4. Character Reconstruction: Finally, it converts the shifted numerical value back into its corresponding character using the chr function. In the next article, we will see how to hack Caesar cipher by using either brute-force or frequency analysis.

More cipher source codes can be found at PythonCipher

Top comments (1)

Collapse
 
balagmadhu profile image
Bala Madhusoodhanan