Cryptography - Caesar Cipher



So the next cryptographic algorithm is Caesar Cipher. In this chapter we will see what exactly Caesar Cipher is, how it works and also its implementations with different techniques. So let us deep dive into it.

What is a Caesar Cipher ?

The Caesar Cipher algorithm is the simple and easy approach of encryption technique. It is a simple type of substitution cipher in which the alphabets are moved by using a selected number of areas to create the encoded message. An A can be encoded as a C, M as an O, a Z as an B, and so on with the usage of a Caesar cipher with a shift of 2. This technique is named after Roman leader Julius Caesar. It is used in his private correspondence. It is one of the simplest and oldest methods to encrypt messages.

Caesar cipher

Algorithm

Here's the algorithm for the Caesar Cipher for encryption and decryption both −

Encryption Algorithm

For encryption algorithm the steps are as follows −

  • Choose a number to be your "shift" value. This number decides how much each letter will move in the alphabet.

  • Start with your message. Look at each letter in your message.

  • Move each letter forward in the alphabet by the chosen shift value. For example, if the shift value is 3, then "A" will become "D", "M" will become "P", and so on.

  • Save the new letter instead of the old one.

  • Continue this for every letter in the message.

Decryption Algorithm

For the decryption algorithm see the steps below −

  • Start with the encrypted message.

  • Know the shift value used for encryption.

  • Look at each letter in the encrypted message.
  • Move each letter back in the alphabet by the shift value to decrypt it. For example, if the shift value is 3, then "D" will become "A", "P" will become "M", and so on.

  • Save the decrypted letter instead of the encrypted one.

  • Continue this for all the letters in the encrypted message.

Implementation

So, we can implement this algorithm in multiple ways in different programming languages. In the sections below, let us explore each of these methods individually −

  • Using Predefined Constants

  • Using Comprehension Techniques

Using Predefined Constants

In this approach, we will use predefined constants that can be accessed through certain libraries. These constants provide the necessary tools for manipulating sequences of characters or other data types. Since these constants are built-in, they must be imported before use.

These constants are often used to access the alphabet or other necessary elements for implementing algorithms, such as encryption or changing data in a certain way.

Example of Encryption

Below is an example of implementing an encryption method using predefined constants for sequence manipulation −

#include <stdio.h>
#include <string.h>

#define ALPHABET "abcdefghijklmnopqrstuvwxyz"

void caesar_cipher(char *text, int shift) {
   int length = strlen(text);
   for (int i = 0; i < length; i++) {
      if (text[i] >= 'a' && text[i] <= 'z') {
         text[i] = ALPHABET[(strchr(ALPHABET, text[i]) - ALPHABET + shift) % 26];
      }
   }
}

int main() {
   char message[] = "hello";
   int shift_value = 3;
   caesar_cipher(message, shift_value);
   printf("Encrypted message: %s\n", message);
   return 0;
}

Output

The output obtained is as follows −

Encrypted message: khoor
#include <iostream>
#include <string>
#include <cstring>  // Include this header for strchr

#define ALPHABET "abcdefghijklmnopqrstuvwxyz"

void caesar_cipher(std::string &text, int shift) {
   for (size_t i = 0; i < text.length(); i++) {
      if (text[i] >= 'a' && text[i] <= 'z') {
         text[i] = ALPHABET[(strchr(ALPHABET, text[i]) - ALPHABET + shift) % 26];
      }
   }
}

int main() {
   std::string message = "hello";
   int shift_value = 3;
   caesar_cipher(message, shift_value);
   std::cout << "Encrypted message: " << message << std::endl;
   return 0;
}

Output

The output produced is as follows −

Encrypted message: khoor
public class CaesarCipher {
   private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";

   public static String caesar_cipher(String text, int shift) {
      char[] textArray = text.toCharArray();
      for (int i = 0; i < textArray.length; i++) {
         if (textArray[i] >= 'a' && textArray[i] <= 'z') {
            int index = ALPHABET.indexOf(textArray[i]);
            textArray[i] = ALPHABET.charAt((index + shift) % 26);
         }
      }
      return new String(textArray);
   }

   public static void main(String[] args) {
      String message = "hello";
      int shift_value = 3;
      String encrypted_msg = caesar_cipher(message, shift_value);
      System.out.println("Encrypted message: " + encrypted_msg);
   }
}

Output

The output obtained is as shown below −

Encrypted message: khoor
import string
def caesar_cipher(text, shift):
   letters = string.ascii_lowercase
   shifted_letters = letters[shift:] + letters[:shift]
   table = str.maketrans(letters, shifted_letters)
   return text.translate(table)
# function execution
message = "hello"
shift_value = 3
encrypted_msg = caesar_cipher(message, shift_value)
print("Encrypted message:", encrypted_msg)

Output

Following is the output of the above code −

Encrypted message: khoor

Decryption Example

To decrypt the above text message we can use the below code in all the different languages −

#include <stdio.h>
#include <string.h>

#define ALPHABET "abcdefghijklmnopqrstuvwxyz"

void caesar_cipher(char *text, int shift) {
   int length = strlen(text);
   for (int i = 0; i < length; i++) {
      if (text[i] >= 'a' && text[i] <= 'z') {
         text[i] = ALPHABET[(strchr(ALPHABET, text[i]) - ALPHABET + shift) % 26];
      }
   }
}

void caesar_decipher(char *text, int shift) {
   // Decryption is the reverse of encryption, so we apply a negative shift
   caesar_cipher(text, -shift);
}

int main() {
   char encrypted_msg[] = "khoor";  // Example encrypted message
   int shift_value = 3;
   caesar_decipher(encrypted_msg, shift_value);
   printf("Decrypted message: %s\n", encrypted_msg);  // Fixed the string termination
   return 0;
}

Output

The output obtained is as follows −

Decrypted message: hello
#include <iostream>
#include <string>
#include <cstring>  // Include this header for strchr

#define ALPHABET "abcdefghijklmnopqrstuvwxyz"

void caesar_cipher(std::string &text, int shift) {
   for (size_t i = 0; i < text.length(); i++) {
      if (text[i] >= 'a' && text[i] <= 'z') {
         text[i] = ALPHABET[(strchr(ALPHABET, text[i]) - ALPHABET + shift) % 26];
      }
   }
}

void caesar_decipher(std::string &text, int shift) {
   // Decryption is the reverse of encryption, so we apply a negative shift
   caesar_cipher(text, -shift);
}

int main() {
   std::string encrypted_msg = "khoor";  // Example encrypted message
   int shift_value = 3;
   caesar_decipher(encrypted_msg, shift_value);
   std::cout << "Decrypted message: " << encrypted_msg << std::endl;
   return 0;
}

Output

The output produced is as follows −

Decrypted message: hello
public class CaesarCipher {
   private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";

   public static String caesar_cipher(String text, int shift) {
      char[] textArray = text.toCharArray();
      for (int i = 0; i < textArray.length; i++) {
         if (textArray[i] >= 'a' && textArray[i] <= 'z') {
            int index = ALPHABET.indexOf(textArray[i]);
            textArray[i] = ALPHABET.charAt((index + shift) % 26);
         }
      }
      return new String(textArray);
   }

   public static String caesar_decipher(String text, int shift) {
      // Decryption is the reverse of encryption, so we apply a negative shift
      return caesar_cipher(text, -shift);
   }

   public static void main(String[] args) {
      String encrypted_msg = "khoor";  // Example encrypted message
      int shift_value = 3;
      String decrypted_msg = caesar_decipher(encrypted_msg, shift_value);
      System.out.println("Decrypted message: " + decrypted_msg);
   }
}

Output

The output obtained is as shown below −

Decrypted message: hello
import string

def caesar_cipher(text, shift):
   letters = string.ascii_lowercase
   shifted_letters = letters[shift:] + letters[:shift]
   table = str.maketrans(letters, shifted_letters)
   return text.translate(table)

def caesar_decipher(text, shift):
   # Decryption is the reverse of encryption, so we apply a negative shift
   return caesar_cipher(text, -shift)

# Decryption
encrypted_msg = "khoor"  # Example encrypted message
shift_value = 3
decrypted_msg = caesar_decipher(encrypted_msg, shift_value)
print("Decrypted message:", decrypted_msg)

Output

Following is the output of the above code −

Decrypted message: hello

Using Comprehension Techniques

Now we are going to use use a comprehension technique to create a new sequence by iterating over each element in the input data. Inside the comprehension, a conditional check is performed to determine if each element meets a certain condition, such as being part of a specific group or category.

The goal is to modify only the elements that fit the condition, leaving others unchanged.

Encryption Example

Here is the implementation of the Caesar Cipher algorithm using comprehension techniques in all the four languages i.e. C, C++, Python and Java −

#include <stdio.h>
#include <string.h>

void caesar_cipher(char *text, int shift) {
   int length = strlen(text);
   for (int i = 0; i < length; i++) {
      if ('A' <= text[i] && text[i] <= 'Z') {
         text[i] = (char)((((text[i] - 65) + shift) % 26) + 65);
      } else if ('a' <= text[i] && text[i] <= 'z') {
         text[i] = (char)((((text[i] - 97) + shift) % 26) + 97);
      }
   }
}

int main() {
   char message[] = "hello everyone";
   int shift_value = 3;
   caesar_cipher(message, shift_value);
   printf("Encrypted message: %s\n", message);
   return 0;
}

Output

The output obtained is as follows −

Encrypted message: khoor hyhubrqh
#include <iostream>
#include <string>

void caesar_cipher(std::string &text, int shift) {
   for (size_t i = 0; i < text.length(); i++) {
      if ('A' <= text[i] && text[i] <= 'Z') {
         text[i] = (char)((((text[i] - 'A') + shift) % 26) + 'A');
      } else if ('a' <= text[i] && text[i] <= 'z') {
         text[i] = (char)((((text[i] - 'a') + shift) % 26) + 'a');
      }
   }
}

int main() {
   std::string message = "hello everyone";
   int shift_value = 3;
   caesar_cipher(message, shift_value);
   std::cout << "Encrypted message: " << message << std::endl;
   return 0;
}

Output

The output produced is as follows −

Encrypted message: khoor hyhubrqh
public class CaesarCipher {
   public static String caesar_cipher(String text, int shift) {
      StringBuilder encryptedText = new StringBuilder();
      for (int i = 0; i < text.length(); i++) {
         char ch = text.charAt(i);
         if ('A' <= ch && ch <= 'Z') {
            encryptedText.append((char)((((ch - 'A') + shift) % 26) + 'A'));
         } else if ('a' <= ch && ch <= 'z') {
            encryptedText.append((char)((((ch - 'a') + shift) % 26) + 'a'));
         } else {
            encryptedText.append(ch);
         }
      }
      return encryptedText.toString();
   }

   public static void main(String[] args) {
      String message = "hello everyone";
      int shift_value = 3;
      String encrypted_msg = caesar_cipher(message, shift_value);
      System.out.println("Encrypted message: " + encrypted_msg);
   }
}

Output

The output obtained is as shown below −

Encrypted message: khoor hyhubrqh
def caesar_cipher(text, shift):
   encrypted_text = ''
   for char in text:
      if 'A' <= char <= 'Z':
         encrypted_text += chr((ord(char) - 65 + shift) % 26 + 65)
      elif 'a' <= char <= 'z':
         encrypted_text += chr((ord(char) - 97 + shift) % 26 + 97)
      else:
         encrypted_text += char
   return encrypted_text

# function execution 
message = "hello everyone"
shift_value = 3
encrypted_msg = caesar_cipher(message, shift_value)
print("Encrypted message:", encrypted_msg)

Output

Following is the output of the above code −

Encrypted message: khoor hyhubrqh

Decryption Example

To create the decryption program for the Caesar Cipher encrypted message, we can reverse the encryption process. Here is the decryption code for the above Caesar Cipher encryption function using comprehension technique −

#include <stdio.h>
#include <string.h>

void caesar_decipher(char *text, int shift) {
   int length = strlen(text);
   for (int i = 0; i < length; i++) {
      if ('A' <= text[i] && text[i] <= 'Z') {
         text[i] = (char)((((text[i] - 65) - shift + 26) % 26) + 65);  // Adding 26 to avoid negative values
      } else if ('a' <= text[i] && text[i] <= 'z') {
         text[i] = (char)((((text[i] - 97) - shift + 26) % 26) + 97);  // Adding 26 to avoid negative values
      }
   }
}

int main() {
   char encrypted_msg[] = "khoor hyhubrqh";  // Example encrypted message
   int shift_value = 3;
   caesar_decipher(encrypted_msg, shift_value);
   printf("Decrypted message: %s\n", encrypted_msg);
   return 0;
}

Output

The output obtained is as follows −

Decrypted message: hello everyone
#include <iostream>
#include <string>

void caesar_decipher(std::string &text, int shift) {
   for (size_t i = 0; i < text.length(); i++) {
      if ('A' <= text[i] && text[i] <= 'Z') {
         text[i] = (char)((((text[i] - 'A') - shift + 26) % 26) + 'A');  // Adding 26 to avoid negative values
      } else if ('a' <= text[i] && text[i] <= 'z') {
         text[i] = (char)((((text[i] - 'a') - shift + 26) % 26) + 'a');  // Adding 26 to avoid negative values
      }
   }
}

int main() {
   std::string encrypted_msg = "khoor hyhubrqh";  // Example encrypted message
   int shift_value = 3;
   caesar_decipher(encrypted_msg, shift_value);
   std::cout << "Decrypted message: " << encrypted_msg << std::endl;
   return 0;
}

Output

The output produced is as follows −

Decrypted message: hello everyone
public class CaesarCipher {
   public static String caesar_decipher(String text, int shift) {
      StringBuilder decryptedText = new StringBuilder();
      for (int i = 0; i < text.length(); i++) {
         char ch = text.charAt(i);
         if ('A' <= ch && ch <= 'Z') {
            decryptedText.append((char)((((ch - 'A') - shift + 26) % 26) + 'A'));  // Adding 26 to avoid negative values
         } else if ('a' <= ch && ch <= 'z') {
            decryptedText.append((char)((((ch - 'a') - shift + 26) % 26) + 'a'));  // Adding 26 to avoid negative values
         } else {
            decryptedText.append(ch);
         }
      }
      return decryptedText.toString();
   }

   public static void main(String[] args) {
      String encrypted_msg = "khoor hyhubrqh";  // Example encrypted message
      int shift_value = 3;
      String decrypted_msg = caesar_decipher(encrypted_msg, shift_value);
      System.out.println("Decrypted message: " + decrypted_msg);
   }
}

Output

The output obtained is as shown below −

Decrypted message: hello everyone
def caesar_decipher(text, shift):
   decrypted_text = ''
   for char in text:
      if 'A' <= char <= 'Z':
         decrypted_text += chr((ord(char) - 65 - shift) % 26 + 65)
      elif 'a' <= char <= 'z':
         decrypted_text += chr((ord(char) - 97 - shift) % 26 + 97)
      else:
         decrypted_text += char
   return decrypted_text

# Function execution
encrypted_msg = "khoor hyhubrqh"
shift_value = 3

# Decryption
decrypted_msg = caesar_decipher(encrypted_msg, shift_value)
print("Decrypted message:", decrypted_msg)

Output

Following is the output of the above code −

Decrypted message: hello everyone

Features of Caesar Cipher

  • Caesar Cipher is one of the easy and oldest encryption method. It utilizes the technique in which we shift each letter in the plaintext by a fixed number of positions to generate the ciphertext.

  • It is easy to implement Caesar Cipher using basic string manipulation and modulo arithmetic operations in programming languages.

  • It can be easily customized by changing the shift value and it allows for different levels of encryption.

  • Encryption and decryption the use of Caesar Cipher are speedy and efficient, but for short messages.

  • As there are only 26 letters within the English alphabet, the keysize of the Caesar cipher is quite small, with best 26 possible keys.

Drawbacks of Caesar Cipher

  • Caesar Cipher has very weak security as it has only 26 possible keys. So this makes it easy for hackers to try all options and decrypt the messages.

  • The fixed alphabet size also makes it vulnerable to frequency analysis attacks, where hackers use the commonness of letters to guess the key.

  • Modifications to the ciphertext can also go undetected because it lacks authentication.

Because of these weaknesses, it is not suitable for modern encryption requirements.

Summary

Caesar Cipher is a simple way to hide messages. It shifts each letter in a message by using a fixed number of spaces. To use it we can choose a number for shift and move every letter by that number to encrypt the message. But it is not very secure because there are only 26 possible keys so attackers can easily guess the code. As they can use letter frequency to guess the actual letter. So with this reason it is not used nowadays.

Advertisements