Caesar Cipher with Implementation

it’s not a gif (;
It is an interactive Caesar Cipher simulation. You can input text and shift value (more on this later) to view the text after encryption and decryption using Caesar Cipher method. Here is the complete code for the above simulation – onlycodeblog/caesarcipher

Caesar Cipher

Caesar Cipher is one of the simplest and oldest encryption techniques, named after Julius Caesar, who used it to protect his military communications. This cipher is a type of substitution cipher where each letter in the plaintext is replaced by a letter a fixed number of positions down or up the alphabet.

How It Works?

Encryption

To encrypt a message, each letter in the plaintext is shifted (to right) by a certain number of positions (often referred to as the ‘key’ or ‘shift’). For example, with a shift of 4,

  • letter 'A' becomes 'E',
  • 'C' becomes 'G',
  • 'O' becomes 'S'

and so on.

Thus, the text `Quick Brown Fox` with a shift value of 4 is encrypted as `Uymgo Fvsar Jsb`.

Decryption

To decrypt the message, the process is reversed by shifting the letters back (to the left) by the same number of positions. For example (let shift value be 2),

  • 'E' -> 'C'
  • 'C' -> 'A'
  • 'V' -> 'T'

Therefore, the text ECV is decrypted as CAT.

Note: Both the lowercase and uppercase letters of the text are preserved during the encryption and decryption process.
Mathematical Representation

Mathematically, the encryption function E can be described as,

E(x) = (x + n) \mod 26

where,

  • x is the position of the letter in the alphabet (e.g., ‘A’ = 0, ‘B’ = 1, …, ‘Z’ = 25),
  • n is the shift/key value and,
  • mod 26 ensures that the shift wraps around the alphabet.

Here, mod is the % (modulo) operator as in C++.

Similarly, decryption function D can be described as,

D(x) = (x - n) \mod 26

Although, Caesar Cipher is easy to understand and implement, it is extremely insecure by modern standards. Since there are only 25 possible shifts (ignoring shift by 0), an attacker can easily brute-force the cipher by trying all possibilities.

Caesar Cipher is primarily used today for educational purposes and is considered a basic introduction to the concept of encryption.

Implementing Caesar Cipher

Let’s implement the Caesar Cipher’s encryption and decryption logic in C++, Java, and Python.

C++ Implementation

#include <iostream>
#include <string>
using namespace std;

string caesarCipherEncrypt(string text, int shift) {
    string result = "";
    shift = shift%26; // for shift values greater than 26

    for (int i = 0; i < text.length(); i++) {
        char c = text[i];

        if (isalpha(c)) {
            char base = isupper(c) ? 'A' : 'a';
            c = (c - base + shift) % 26 + base;
        }

        result += c;
    }

    return result;
}

string caesarCipherDecrypt(string text, int shift) {
    return caesarCipherEncrypt(text, 26 - shift);
}

int main() {
    string text = "Hello World";
    int shift = 3;

    string encrypted = caesarCipherEncrypt(text, shift);
    string decrypted = caesarCipherDecrypt(encrypted, shift);

    cout << "Original Text: " << text << endl;
    cout << "Encrypted Text: " << encrypted << endl;
    cout << "Decrypted Text: " << decrypted << endl;

    return 0;
}

Java Implementation

public class CaesarCipher {
    public static String encrypt(String text, int shift) {
        StringBuilder result = new StringBuilder();
        shift = shift%26; // for shift values greater than 26

        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);

            if (Character.isLetter(c)) {
                char base = Character.isUpperCase(c) ? 'A' : 'a';
                c = (char) ((c - base + shift) % 26 + base);
            }

            result.append(c);
        }

        return result.toString();
    }

    public static String decrypt(String text, int shift) {
        return encrypt(text, 26 - shift);
    }

    public static void main(String[] args) {
        String text = "Hello World";
        int shift = 3;

        String encrypted = encrypt(text, shift);
        String decrypted = decrypt(encrypted, shift);

        System.out.println("Original Text: " + text);
        System.out.println("Encrypted Text: " + encrypted);
        System.out.println("Decrypted Text: " + decrypted);
    }
}

Python Implementation

def encrypt(text, shift):
    result = ""
    shift = shift%26; # for shift values greater than 26

    for i in range(len(text)):
        char = text[i]

        if char.isalpha():
            base = ord('A') if char.isupper() else ord('a')
            result += chr((ord(char) - base + shift) % 26 + base)
        else:
            result += char

    return result

def decrypt(text, shift):
    return encrypt(text, 26 - shift)

if __name__ == "__main__":
    text = "Hello World"
    shift = 3

    encrypted = encrypt(text, shift)
    decrypted = decrypt(encrypted, shift)

    print(f"Original Text: {text}")
    print(f"Encrypted Text: {encrypted}")
    print(f"Decrypted Text: {decrypted}")

Output

Original Text: Hello World
Encrypted Text: Khoor Zruog
Decrypted Text: Hello World

Code Explanation

Input

Each program accepts a string (text) and an integer (shift). The integer represents how many positions each character should be shifted lexicographically in the alphabet.

Encryption (Character Shifting)

  • Uppercase and Lowercase Letters: The programs check if the character is a letter. If so, it shifts it according to the shift while keeping its case intact. The modulo operation (%) ensures that we wrap around the alphabet for the shift greater than the last alphabet (ie. after ‘Z’ comes ‘A’).
  • Non-letter Characters: Any characters that are not letters (e.g., numerals, symbols, punctuation or spaces) are not modified.

Decryption

Decryption is essentially the reverse of encryption ie. instead of moving forward, we move backward by the shift value.
However, in the code used for decryption, we shift forward by 26 - shift rather than shifting back by shift, effectively reversing the encryption. (This is so that, we can use the same logic as encryption for decryption ie. shifting forward)

Decryption Logic

Imagine a simplified alphabet consisting of just 5 characters (A, B, C, D, E) and to mimic the modulo (%) operation, lets use a circular queue.

The circular queue would look like this:

A -> B -> C -> D -> E -> A -> B -> C -> D -> E -> ...

In this setup, each position is connected circularly, meaning after E, you loop back to A. This is analogous to the behavior of the modulo operation, where numbers cycle back to the beginning after reaching the value of divisor (ie. 5 here).

By visualizing the characters in a circular queue, this becomes much easier to understand:
– Starting at A (position 0), moving forward by 6 steps brings you to B.
– In modulo terms: 6 % 5 = 1, so you're effectively starting over from the beginning (A) and landing on B.

This way, modulo operation ensures that you always stay within the bounds of the alphabet, no matter how large the shift value is.

--------------------------------------------------------

A -> B -> C -> D -> E -> A -> B -> C -> D -> E -> ...

Now, consider you have an encrypted text and want to decrypt it by moving backwards in the circular queue. Suppose the letter you are currently on is E, and you need to decrypt it to B using a shift value of 3.

There are two ways you can think about this movement:
- moving backward by the shift value (3): B <- C <- D <- E
- or, moving forward by the `complement` of the shift value ie. 2 (calculated as 5 - shift): E -> A -> B

This explains how we decrypt the text using the same logic as the encrypt procedure.

Caesar Cipher is a great way to get started with encryption and decryption concepts. While it is a very basic and insecure form of encryption (since it can be easily brute-forced), it demonstrates the core ideas of cryptography: substitution and reversible transformations of data.

So, that’s the Caesar Cipher and its implementation; hope you found it useful.

Leave a Reply

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