The Caesar Cipher technique is one of the earliest and simplest methods of encryption technique. 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. 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.
(Encryption Phase with shift n)
(Decryption Phase with shift n)
Text : ABCDEFGHIJKLMNOPQRSTUVWXYZ
Text : ATTACKATONCE
Algorithm for Caesar Cipher: Input:
A String of lower case letters, called Text.
An Integer between 0-25 denoting the required shift.
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.
// A C++ program to illustrate Caesar Cipher Technique
// This function receives text and shift and
// returns the encrypted text
string encrypt(string text, ints)
string result = "";
// traverse text
// apply transformation to each character
// Encrypt Uppercase letters
result += char(int(text[i]+s-65)%26 +65);
// Encrypt Lowercase letters
result += char(int(text[i]+s-97)%26 +97);
// Return the resulting string
// Driver program to test the above function
ints = 4;
cout << "Text : "<< text;
cout << "\nShift: "<< s;
cout << "\nCipher: "<< encrypt(text, s);
//A Java Program to illustrate Caesar Cipher Technique
// This code is contributed by avanitrachhadiya2155
Text : ATTACKATONCE
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++).
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 email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.