Caesar Cipher in Cryptography - GeeksforGeeks

22 Jan, 2022
The Caesar Cipher technique is one of the earliest and simplest method of encryption technique. It’s simply a type of substitution cipher, i.e., each letter of a given text is replaced by a letter some 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. Thus to cipher a given text we need an integer value, known as shift which indicates the number of position 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.  
(Encryption Phase with shift n)
(Decryption Phase with shift n)
Examples :  
Text : ABCDEFGHIJKLMNOPQRSTUVWXYZ
Shift: 23
Cipher: XYZABCDEFGHIJKLMNOPQRSTUVW

Text : ATTACKATONCE
Shift: 4
Cipher: EXXEGOEXSRGI
Algorithm for Caesar Cipher: Input:  
A String of lower case letters, called Text.An Integer between 0-25 denoting the required shift.
A String of lower case letters, called Text.
An Integer between 0-25 denoting the required shift.
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.
Program that receives a Text (string) and Shift value( integer) and returns the encrypted text.  
C++
Java
Python3
C#
PHP
Javascript
// A C++ program to illustrate Caesar Cipher Technique#include <iostream>using namespace std; // This function receives text and shift and// returns the encrypted textstring 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 functionint main(){    string text="ATTACKATONCE";    int s = 4;    cout << "Text : " << text;    cout << "\nShift: " << s;    cout << "\nCipher: " << encrypt(text, s);    return 0;}
//A Java Program to illustrate Caesar Cipher Techniqueclass CaesarCipher{    // Encrypts text using a shift od 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));    }}
#A python program to illustrate Caesar Cipher Techniquedef 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 functiontext = "ATTACKATONCE"s = 4print ("Text  : " + text)print ("Shift : " + str(s))print ("Cipher: " + encrypt(text,s))
// A C# Program to illustrate Caesar Cipher Techniqueusing System;using System.Text; public class CaesarCipher{    // Encrypts text using a shift od 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 */
<?php// A PHP program to illustrate Caesar// Cipher Technique // This function receives text and shift// and returns the encrypted textfunction 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?>
<script>//A Javascript Program to illustrate Caesar Cipher Technique         // Encrypts text using a shift od 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>
Output:  
Text : ATTACKATONCE
Shift: 4
Cipher: EXXEGOEXSRGI
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 this for a sample run in C++). 
https://www.youtube.com/watch?v=S472gPqwF
-o 
 
 
This article is contributed by Ashutosh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
 
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
 
SOURABH MANGAL
ukasp
princiraj1992
avanitrachhadiya2155
amartyaniel20
cryptography
Computer Networks
GATE CS
Strings
Strings
cryptography
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between IPv4 and IPv6
Types of Network Topology
TCP 3-Way Handshake Process
UDP Server-Client implementation in C
User Datagram Protocol (UDP)
ACID Properties in DBMS
Types of Operating Systems
Normal Forms in DBMS
Page Replacement Algorithms in Operating Systems
Cache Memory in Computer Organization