The Wayback Machine - https://web.archive.org/web/20241122232721/https://www.geeksforgeeks.org/caesar-cipher-in-cryptography/
Open In App

Caesar Cipher in Cryptography

Last Updated : 27 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The Caesar Cipher is one of the simplest and oldest methods of encrypting messages, named after Julius Caesar, who reportedly used it to protect his military communications. This technique involves shifting the letters of the alphabet by a fixed number of places. For example, with a shift of three, the letter ‘A’ becomes ‘D’, ‘B’ becomes ‘E’, and so on. Despite its simplicity, the Caesar Cipher formed the groundwork for modern cryptographic techniques. In this article, we’ll explore how the Caesar Cipher works, its significance, and its impact on the development of cryptography with its advantages and disadvantages.

What is Caesar Cipher Technique?

The Caesar cipher is a simple encryption technique that was used by Julius Caesar to send secret messages to his allies. It works by shifting the letters in the plaintext message by a certain number of positions, known as the “shift” or “key”. The Caesar Cipher technique is one of the earliest and simplest methods of encryption techniques.

It’s simply a type of substitution cipher, i.e., each letter of a given text is replaced by a letter with a fixed number of positions down the alphabet. For example with a shift of 1, A would be replaced by B, B would become C, and so on. The method is apparently named after Julius Caesar, who apparently used it to communicate with his officials.

Cryptography Algorithm For the Caesar Cipher

  • Thus to cipher a given text we need an integer value, known as a shift which indicates the number of positions each letter of the text has been moved down. 
    The encryption can be represented using modular arithmetic by first transforming the letters into numbers, according to the scheme, A = 0, B = 1,…, Z = 25. Encryption of a letter by a shift n can be described mathematically as. 
  • For example, if the shift is 3, then the letter A would be replaced by the letter D, B would become E, C would become F, and so on. The alphabet is wrapped around so that after Z, it starts back at A.
  • Here is an example of how to use the Caesar cipher to encrypt the message “HELLO” with a shift of 3:
  1. Write down the plaintext message: HELLO
  2. Choose a shift value. In this case, we will use a shift of 3.
  3. Replace each letter in the plaintext message with the letter that is three positions to the right in the alphabet.

 H becomes K (shift 3 from H)       
 E becomes H (shift 3 from E)   
 L becomes O (shift 3 from L)       
L becomes O (shift 3 from L)         
O becomes R (shift 3 from O)

      4.The encrypted message is now “KHOOR”.

  • To decrypt the message, you simply need to shift each letter back by the same number of positions. In this case, you would shift each letter in “KHOOR” back by 3 positions to get the original message, “HELLO”.


[Tex]E_n(x)=(x+n)mod\ 26                 [/Tex]
(Encryption Phase with shift n)

[Tex]D_n(x)=(x-n)mod\ 26                 [/Tex]
(Decryption Phase with shift n)

Caesar Cipher Technique

Examples : 

Text : ABCDEFGHIJKLMNOPQRSTUVWXYZ
Shift: 23
Cipher: XYZABCDEFGHIJKLMNOPQRSTUVW

Text : ATTACKATONCE
Shift: 4
Cipher: EXXEGOEXSRGI

Advantages

  • Easy to implement and use thus, making suitable for beginners to learn about encryption.
  • Can be physically implemented, such as with a set of rotating disks or a set of cards, known as a scytale, which can be useful in certain situations.
  • Requires only a small set of pre-shared information.
  • Can be modified easily to create a more secure variant, such as by using a multiple shift values or keywords.

Disadvantages

  • It is not secure against modern decryption methods.
  • Vulnerable to known-plaintext attacks, where an attacker has access to both the encrypted and unencrypted versions of the same messages.
  • The small number of possible keys means that an attacker can easily try all possible keys until the correct one is found, making it vulnerable to a brute force attack.
  • It is not suitable for long text encryption as it would be easy to crack.
  • It is not suitable for secure communication as it is easily broken.
  • Does not provide confidentiality, integrity, and authenticity in a message. 

Features of Caesar Cipher

  1. Substitution cipher: The Caesar cipher is a type of substitution cipher, where each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet.
  2. Fixed key: The Caesar cipher uses a fixed key, which is the number of positions by which the letters are shifted. This key is known to both the sender and the receiver.
  3. Symmetric encryption: The Caesar cipher is a symmetric encryption technique, meaning that the same key is used for both encryption and decryption.
  4. Limited keyspace: The Caesar cipher has a very limited keyspace of only 26 possible keys, as there are only 26 letters in the English alphabet.
  5. Vulnerable to brute force attacks: The Caesar cipher is vulnerable to brute force attacks, as there are only 26 possible keys to try.
  6. Easy to implement: The Caesar cipher is very easy to implement and requires only simple arithmetic operations, making it a popular choice for simple encryption tasks.

Rules for the Caesar Cipher

  1. Choose a number between 1 and 25. This will be your “shift” value.
  2. Write down the letters of the alphabet in order, from A to Z.
  3. Shift each letter of the alphabet by the “shift” value. For example, if the shift value is 3, A would become D, B would become E, C would become F, and so on.
  4. Encrypt your message by replacing each letter with the corresponding shifted letter. For example, if the shift value is 3, the word “hello” would become “khoor”.
  5. To decrypt the message, simply reverse the process by shifting each letter back by the same amount. For example, if the shift value is 3, the encrypted message “khoor” would become “hello”.

Algorithm for Caesar Cipher

Input: 

  1. Choose a shift value between 1 and 25.
  2. Write down the alphabet in order from A to Z.
  3. Create a new alphabet by shifting each letter of the original alphabet by the shift value. For example, if the shift value is 3, the new alphabet would be:
  4. 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
    D E F G H I J K L M N O P Q R S T U V W X Y Z A B C
  5. Replace each letter of the message with the corresponding letter from the new alphabet. For example, if the shift value is 3, the word “hello” would become “khoor”.
  6. To decrypt the message, shift each letter back by the same amount. For example, if the shift value is 3, the encrypted message “khoor” would become “hello”.

Procedure: 

  • Traverse the given text one character at a time .
  • For each character, transform the given character as per the rule, depending on whether we’re encrypting or decrypting the text.
  • Return the new string generated.

A program that receives a Text (string) and Shift value( integer) and returns the encrypted text. 

C++
// A C++ program to illustrate Caesar Cipher Technique
#include <iostream>
using namespace std;

// This function receives text and shift and
// returns the encrypted text
string encrypt(string text, int s)
{
    string result = "";

    // traverse text
    for (int i = 0; i < text.length(); i++) {
        // apply transformation to each character
        // Encrypt Uppercase letters
        if (isupper(text[i]))
            result += char(int(text[i] + s - 65) % 26 + 65);

        // Encrypt Lowercase letters
        else
            result += char(int(text[i] + s - 97) % 26 + 97);
    }

    // Return the resulting string
    return result;
}

// Driver program to test the above function
int main()
{
    string text = "ATTACKATONCE";
    int s = 4;
    cout << "Text : " << text;
    cout << "\nShift: " << s;
    cout << "\nCipher: " << encrypt(text, s);
    return 0;
}
Java
//A Java Program to illustrate Caesar Cipher Technique
class CaesarCipher
{
    // Encrypts text using a shift of s
    public static StringBuffer encrypt(String text, int s)
    {
        StringBuffer result= new StringBuffer();

        for (int i=0; i<text.length(); i++)
        {
            if (Character.isUpperCase(text.charAt(i)))
            {
                char ch = (char)(((int)text.charAt(i) +
                                  s - 65) % 26 + 65);
                result.append(ch);
            }
            else
            {
                char ch = (char)(((int)text.charAt(i) +
                                  s - 97) % 26 + 97);
                result.append(ch);
            }
        }
        return result;
    }

    // Driver code
    public static void main(String[] args)
    {
        String text = "ATTACKATONCE";
        int s = 4;
        System.out.println("Text  : " + text);
        System.out.println("Shift : " + s);
        System.out.println("Cipher: " + encrypt(text, s));
    }
}
Python
#A python program to illustrate Caesar Cipher Technique
def encrypt(text,s):
    result = ""

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

        # Encrypt uppercase characters
        if (char.isupper()):
            result += chr((ord(char) + s-65) % 26 + 65)

        # Encrypt lowercase characters
        else:
            result += chr((ord(char) + s - 97) % 26 + 97)

    return result

#check the above function
text = "ATTACKATONCE"
s = 4
print ("Text  : " + text)
print ("Shift : " + str(s))
print ("Cipher: " + encrypt(text,s))
C#
// A C# Program to illustrate Caesar Cipher Technique
using System;
using System.Text; 

public class CaesarCipher
{
    // Encrypts text using a shift on s
    public static StringBuilder encrypt(String text, int s)
    {
        StringBuilder result= new StringBuilder();

        for (int i=0; i<text.Length; i++)
        {
            if (char.IsUpper(text[i]))
            {
                char ch = (char)(((int)text[i] +
                                s - 65) % 26 + 65);
                result.Append(ch);
            }
            else
            {
                char ch = (char)(((int)text[i] +
                                s - 97) % 26 + 97);
                result.Append(ch);
            }
        }
        return result;
    }

    // Driver code
    public static void Main(String[] args)
    {
        String text = "ATTACKATONCE";
        int s = 4;
        Console.WriteLine("Text : " + text);
        Console.WriteLine("Shift : " + s);
        Console.WriteLine("Cipher: " + encrypt(text, s));
    }
}

/* This code contributed by PrinciRaj1992 */
JavaScript
<script>
//A Javascript Program to illustrate Caesar Cipher Technique
    
    // Encrypts text using a shift on s
    function encrypt(text, s)
    {
        let result=""
        for (let i = 0; i < text.length; i++)
        {
            let char = text[i];
            if (char.toUpperCase(text[i]))
            {
                let ch =  String.fromCharCode((char.charCodeAt(0) + s-65) % 26 + 65);
                result += ch;
            }
            else
            {
                let ch = String.fromCharCode((char.charCodeAt(0) + s-97) % 26 + 97);
                result += ch;
            }
        }
        return result;
    }
    
    // Driver code
    let text = "ATTACKATONCE";
    let s = 4;
    document.write("Text  : " + text + "<br>");
    document.write("Shift : " + s + "<br>");
    document.write("Cipher: " + encrypt(text, s) + "<br>");
    
    //  This code is contributed by avanitrachhadiya2155
</script>
PHP
<?php
// A PHP program to illustrate Caesar
// Cipher Technique

// This function receives text and shift 
// and returns the encrypted text
function encrypt($text, $s)
{
    $result = "";

    // traverse text
    for ($i = 0; $i < strlen($text); $i++)
    {
        // apply transformation to each 
        // character Encrypt Uppercase letters
        if (ctype_upper($text[$i]))
            $result = $result.chr((ord($text[$i]) + 
                               $s - 65) % 26 + 65);

    // Encrypt Lowercase letters
    else
        $result = $result.chr((ord($text[$i]) + 
                           $s - 97) % 26 + 97);
    }

    // Return the resulting string
    return $result;
}

// Driver Code
$text = "ATTACKATONCE";
$s = 4;
echo "Text : " . $text;
echo "\nShift: " . $s;
echo "\nCipher: " . encrypt($text, $s);

// This code is contributed by ita_c
?>

Output
Text : ATTACKATONCE
Shift: 4
Cipher: EXXEGOEXSRGI

Time complexity: O(N) where N is length of the given text
Auxiliary space: O(N)

How to decrypt? 
We can either write another function decrypt similar to encrypt, that’ll apply the given shift in the opposite direction to decrypt the original text. However we can use the cyclic property of the cipher under modulo, hence we can simply observe 

Cipher(n) = De-cipher(26-n)

Hence, we can use the same function to decrypt, instead, we’ll modify the shift value such that shift = 26-shift (Refer to this for a sample run in C++).

Conclusion

The Caesar Cipher, with its straightforward approach of shifting letters, serves as an excellent introduction to the world of cryptography. While it is easy to understand and implement, its simplicity also makes it vulnerable to basic attacks. Despite these limitations, the Caesar Cipher’s historical role is significant, it represents the early efforts to secure communication and has made the way for the more advanced encryption methods used today. Understanding the Caesar Cipher helps us appreciate the evolution of cryptographic techniques and the ongoing quest to protect information in our digital age.

Frequently Asked Question on Caesar Cipher in Cryptography -FAQs

What is the Caesar cipher in cryptography?

The Caesar Cipher, used by Julius Caesar around 58 BC, is a method that scrambles a message by shifting its letters. For example, shifting ‘A’ by three positions makes it ‘D’. To read the message, the receiver reverses this shift. Later, an Arab mathematician cracked the Caesar Cipher by analyzing how often each letter appears, which helped him figure out the pattern and decode the message.

What is an example of decryption in Caesar cipher?

An example of decryption in the Caesar cipher is decrypting the message KHOOR. If the original shift used to encrypt the message was 3, you would reverse this by shifting each letter back by 3 places in the alphabet. Thus, K shifts to H, H to E, O to L, and R to O, revealing the decrypted message: HELLO.

What are keys in Caesar cipher?

In the Caesar cipher, the key is a letter that shows how many places to shift each letter in the message. For example, a key D means “shift 3 places,” and a key M means “shift 12 places.” A key A means “do not shift,” and a key Z means either “shift 25 places” or “shift one place backwards.”



Previous Article
Next Article

Similar Reads

Difference between Block Cipher and Transposition Cipher
1. Block Cipher :  Block Cipher is the symmetric key cipher used for converting the plain text into cipher text. It uses a simple substitution process or sometimes the permutation process where the block of plain text is substituted with arbitrary bit of cipher text.    2. Transposition Cipher :  Transposition Cipher rearranges the position of the
2 min read
Difference between Monoalphabetic Cipher and Polyalphabetic Cipher
A Monoalphabetic Cipher is a cipher where each letter in the plaintext is always mapped to the same letter in the ciphertext While a Polyalphabetic Cipher is a cipher where each letter in the plaintext can be encrypted to multiple possible letters in the ciphertext, depending on its position and a more complex algorithm. In this article, we will se
3 min read
Difference between Substitution Cipher Technique and Transposition Cipher Technique
An encryption algorithm, or cipher, is a means of transforming plaintext into ciphertext under the control of a secret key. Cryptographic algorithms are classified as Symmetric key cryptography and Asymmetric key cryptography. All encryption algorithms are based on two general principles. substitution, in which each element in the plaintext(bit, le
4 min read
Difference between Block Cipher and Stream Cipher
Block Cipher and Stream Cipher are the types of symmetric key cipher. These two block ciphers are used to transform plain text into ciphertext. The difference between a Block cipher and a Stream cipher is that the former transforms the plain text into cipher text by taking the plain text block by block. On the other hand, a block cipher produces ci
5 min read
Bifid Cipher in Cryptography
This cipher technique considered more secure compared to other substitution algorithms reason being it breaks the message apart into two separate streams and then recombines them. It is a combination of the Polybius square with the transposition and uses fractionation to achieve diffusion. This encrypting technique invented by Felin Delastelle. It
4 min read
Vernam Cipher in Cryptography
Vernam Cipher is a method of encrypting alphabetic text. It is one of the Substitution techniques for converting plain text into cipher text. In this mechanism, we assign a number to each character of the Plain-Text, like (a = 0, b = 1, c = 2, ... z = 25). Method to take key: In the Vernam cipher algorithm, we take a key to encrypt the plain text w
6 min read
Transposition Cipher Techniques in Cryptography
Transposition Ciphers are an essential part of cryptography that uses systematic shuffling of plain text characters or bits to secure data by altering their positions based on some defined way or algorithm. Moreover, unlike substitutive codes where different letters substitute others, in these, you just shift about original letters hence it does no
5 min read
What is Multiplicative Cipher in Cryptography?
A multiplicative cipher is a type of cipher that comes under a monoalphabetic cipher, in which each letter that is present in the plaintext is replaced by a corresponding letter of the ciphertext, according to a fixed multiplication key. In this article, we will learn about the multiplicative cipher and its working for the encryption and decryption
9 min read
Classical Cryptography and Quantum Cryptography
Cryptography is the technique that is used for secure communication between two parties in a public environment where unauthorized users and malicious attackers are present. In cryptography, there are two processes i.e. encryption and decryption performed at the sender and receiver end respectively. Encryption is the process where simple multimedia
7 min read
Latin alphabet cipher
The Latin Alphabet Cipher Encryption Technique is one of the earliest and simplest techniques of encrypting data. It’s simply a type of substitution cipher technique, i.e., each letter of a given text is substituted by its corresponding number as represented in its alphabetical order. For Example, we have given a string as "hello everyone", then it
5 min read
Transforming a Plain Text message to Cipher Text
There are two primary ways in which a plain text can be modified to obtain cipher text: Substitution Technique and Transposition Technique. 1. Substitution Technique: Substitution technique involves the replacement of the letters by other letters and symbols. In a more straightforward way, the characters of plaintext are replaced, and other substit
6 min read
Feistel Cipher
Feistel Cipher model is a structure or a design used to develop many block ciphers such as DES. Feistel cipher may have invertible, non-invertible and self invertible components in its design. Same encryption as well as decryption algorithm is used. A separate key is used for each round. However same round keys are used for encryption as well as de
3 min read
Encrypt using XOR Cipher with Repeating Key
Computer Architectures have predefined ASCII values & Binary forms for all printable characters, which allows us to operate bit-wise logic like XOR and most encryption/decryption algorithms depend on. The Key is XOR-operated on the plain text to produce the encrypted text. Only Parameters required to encrypt a plain text using this technique: P
2 min read
Block Cipher Design Principles
Block ciphers are built in the Feistel cipher structure. Block cipher has a specific number of rounds and keys for generating ciphertext.Block cipher is a type of encryption algorithm that processes fixed-size blocks of data, usually 64 or 128 bits, to produce ciphertext. The design of a block cipher involves several important principles to ensure
3 min read
Program to perform a letter frequency attack on a monoalphabetic substitution cipher
Given a string S of size N representing a monoalphabetic cipher, the task is to print the top five possible plain texts that can be decrypted from the given monoalphabetic cipher using a letter frequency attack. Examples: Input: S = "ETAOINSHRDLCUMWFGYPBVKJXQZ"Output: A SIMPLE MESSAGE B TJNQMF NFTTBHF A SIMPLE MESSAGE C UKORNG OGUUCIG C UKORNG OGUU
13 min read
Symmetric Cipher Model
Symmetric Encryption is the most basic and old method of encryption. It uses only one key for the process of both the encryption and decryption of data. Thus, it is also known as Single-Key Encryption. A few basic terms in Cryptography are as follows: Plain Text: original message to be communicated between sender and receiver Cipher Text: encoded f
3 min read
Implementation of Vernam Cipher or One Time Pad Algorithm
One Time Pad algorithm is the improvement of the Vernam Cipher, proposed by An Army Signal Corp officer, Joseph Mauborgne. It is the only available algorithm that is unbreakable(completely secure). It is a method of encrypting alphabetic plain text. It is one of the Substitution techniques which converts plain text into ciphertext. In this mechanis
13 min read
XOR Cipher
XOR Encryption is an encryption method used to encrypt data and is hard to crack by brute-force method, i.e generating random encryption keys to match with the correct one. Below is a simple implementation in C++. The concept of implementation is to first define XOR - encryption key and then to perform XOR operation of the characters in the String
5 min read
Rail Fence Cipher - Encryption and Decryption
Given a plain-text message and a numeric key, cipher/de-cipher the given text using Rail Fence algorithm. The rail fence cipher (also called a zigzag cipher) is a form of transposition cipher. It derives its name from the way in which it is encoded. Examples:  EncryptionInput : "GeeksforGeeks "Key = 3Output : GsGsekfrek eoeDecryptionInput : GsGsekf
15 min read
Implementation of Affine Cipher
The Affine cipher is a type of monoalphabetic substitution cipher, wherein each letter in an alphabet is mapped to its numeric equivalent, encrypted using a simple mathematical function, and converted back to a letter. The formula used means that each letter encrypts to one other letter, and back again, meaning the cipher is essentially a standard
10 min read
ROT13 cipher
ROT13 cipher(read as - "rotate by 13 places") is a special case of the Ceaser cipher in which the shift is always 13. So every letter is shifted 13 places to encrypt or to decrypt the message. You must think that it is just another caesar cipher so what's different this time? Well the difference is in its implementation. The approach is to use two
10 min read
Implementing Atbash Cipher
Definition: Atbash cipher is a substitution cipher with just one specific key where all the letters are reversed that is A to Z and Z to A. It was originally used to encode the Hebrew alphabets but it can be modified to encode any alphabet. Relationship to Affine: Atbash cipher can be thought of as a special case of Affine cipher with both the keys
7 min read
Keyword Cipher
Keyword cipher is a form of monoalphabetic substitution. A keyword is used as the key, and it determines the letter matchings of the cipher alphabet to the plain alphabet. Repeats of letters in the word are removed, then the cipher alphabet is generated with the keyword matching to A, B, C, etc. until the keyword is used up, whereupon the rest of t
15+ min read
Null Cipher
A null cipher, also known as concealment cipher, is an ancient form of encryption where the plaintext is mixed with a large amount of non-cipher material. Today it is regarded as a simple form of steganography, which can be used to hide ciphertext. There are various options of using the Null Cipher. Here we are taking the first letter from each wor
6 min read
Columnar Transposition Cipher
Given a plain-text message and a numeric key, cipher/de-cipher the given text using Columnar Transposition Cipher The Columnar Transposition Cipher is a form of transposition cipher just like Rail Fence Cipher. Columnar Transposition involves writing the plaintext out in rows, and then reading the ciphertext off in columns one by one. Examples: Enc
12 min read
What is Round Cipher?
Round ciphers are also known as block ciphers, and they are a classification of encryption algorithms that work systematically, converting the plaintext into ciphertext. These algorithms work on a limited number of bits at a time and subject them to a set of mathematical processes called rounds which are used to bring about the act of encryption. I
10 min read
What is Cipher?
Ciphers are the most vital components of cryptography, as it is through them that the protection of information is made possible in the ever-growing digital environment. In the present generation, given the technological advancement especially in the field of communication, the aspect of security is critical. Cipher is used in securing financial tr
7 min read
What is Monoalphabetic Cipher?
Monoalphabetic Cipher is a part of the substitution technique in which a single cipher alphabet is used per message (mapping is done from plain alphabet to cipher alphabet). Monoalphabetic cipher converts plain text into cipher text and re-convert a cipher text to plain text. Monoalphabetic Cipher eliminates the brute-force techniques for cryptanal
4 min read
VigenÃĻre Cipher
Vigenere Cipher is a method of encrypting alphabetic text. It uses a simple form of polyalphabetic substitution. A polyalphabetic cipher is any cipher based on substitution, using multiple substitution alphabets. The encryption of the original text is done using the VigenÃĻre square or VigenÃĻre table. The table consists of the alphabets written out
9 min read
Playfair Cipher with Examples
The Playfair cipher was the first practical digraph substitution cipher. The scheme was invented in 1854 by Charles Wheatstone but was named after Lord Playfair who promoted the use of the cipher. In playfair cipher unlike traditional cipher we encrypt a pair of alphabets(digraphs) instead of a single alphabet.It was used for tactical purposes by B
15+ min read
Practice Tags :
three90RightbarBannerImg