Caesar Cipher
The Caesar cipher, also known as the shift cipher, is one of the simplest and most widely known encryption techniques. It is named after Julius Caesar, who is said to have used it to communicate with his officials.
The Caesar cipher works by shifting each letter in the plaintext by a certain number of places down the alphabet. For example, with a shift of 3, A would be replaced by D, B would become E, and so on. The encryption and decryption process can be represented using the following formula:
Encryption: E(x) = (x + n) mod 26 Decryption: D(x) = (x - n) mod 26
where x is the numerical value of the plaintext letter (A=0, B=1, C=2, and so on), n is the number of positions to shift, and mod 26 means that if the result is greater than 25 (the number of letters in the alphabet), it wraps around to the beginning of the alphabet.
For example, with a shift of 3, the plaintext "HELLO" would be encrypted as "KHOOR" using the following table:
Plaintext: H E L L O Numerical value: 7 4 11 11 14 Shift: +3 +3 +3 +3 +3 Ciphertext: K H O O R
The Caesar cipher is easily broken, however, as there are only 26 possible shifts, and an attacker can easily try all of them to decode the message.
Java example
import java.util.Scanner;
public class CaesarCipher
{
public static void main(String[] args)
{
String plaintext = "NEWiceCream";
int shift = 12;
String ciphertext = encrypt(plaintext, shift);
String decryptedtext = decrypt(ciphertext, shift);
System.out.println("Ciphertext: " + ciphertext);
System.out.println("Decrypted text: " + decryptedtext);
}
public static String encrypt(String plaintext, int shift)
{
String ciphertext = "";
for (int i = 0; i < plaintext.length(); i++)
{
char ch = plaintext.charAt(i);
if (ch >= 'a' && ch <= 'z')
{
ch = (char)((ch - 'a' + shift) % 26 + 'a');
}
else if (ch >= 'A' && ch <= 'Z')
{
ch = (char)((ch - 'A' + shift) % 26 + 'A');
}
ciphertext += ch;
}
return ciphertext;
}
public static String decrypt(String ciphertext, int shift)
{
String decryptedtext = "";
for (int i = 0; i < ciphertext.length(); i++)
{
char ch = ciphertext.charAt(i);
if (ch >= 'a' && ch <= 'z')
{
ch = (char)((ch - 'a' - shift + 26) % 26 + 'a');
}
else if (ch >= 'A' && ch <= 'Z')
{
ch = (char)((ch - 'A' - shift + 26) % 26 + 'A');
}
decryptedtext += ch;
}
return decryptedtext;
}
}
This complete Java program that implements the Caesar cipher encryption and decryption.
The program sets a plaintext string and a shift value, then uses the encrypt()
method to encrypt the plaintext and the decrypt()
method to decrypt the resulting ciphertext. The encrypt()
and decrypt()
methods use the encryption and decryption formulas discussed earlier.
When you run the program, it will output the ciphertext and the decrypted text. In this case, since the plaintext is "NEWiceCream" and the shift is 12, the resulting ciphertext should be "ZQIupqOmyixs" and the decrypted text should be "NEWiceCream".
Ciphertext: ZQIuoqOdqmy Decrypted text: NEWiceCream
Simple other code.
/*
Java program for
Caesar Cipher
*/
public class CaesarCipher
{
String encryptText(String text, int shift)
{
String output = "";
// Execute loop through by length of given text
for (int i = 0; i < text.length(); ++i)
{
if (text.charAt(i) >= 'A' &&
text.charAt(i) <= 'Z')
{
// When character is uppercase letter
output = output + (char)(
(int)((text.charAt(i) + shift - 65) % 26) + 65
);
}
else
{
output = output + (char)(
(int)((text.charAt(i) + shift - 97) % 26) + 97
);
}
}
return output;
}
public static void main(String[] args)
{
CaesarCipher task = new CaesarCipher();
String text = "NEWiceCream";
int shift = 12;
String encrypt = task.encryptText(text, shift);
// Display result
System.out.println(" Given text : " + text);
System.out.println(" Encrypt text : " + encrypt);
}
}
Output
Given text : NEWiceCream
Encrypt text : ZQIuoqOdqmy
// Include header file
#include <iostream>
#include <string>
using namespace std;
/*
C++ program for
Caesar Cipher
*/
class CaesarCipher
{
public: string encryptText(string text, int shift)
{
string output = "";
// Execute loop through by length of given text
for (int i = 0; i < text.length(); ++i)
{
if (text[i] >= 'A' && text[i] <= 'Z')
{
// When character is uppercase letter
output = output + (char)(
(int)((text[i] + shift - 65) % 26) + 65
);
}
else
{
output = output + (char)(
(int)((text[i] + shift - 97) % 26) + 97
);
}
}
return output;
}
};
int main()
{
CaesarCipher *task = new CaesarCipher();
string text = "NEWiceCream";
int shift = 12;
string encrypt = task->encryptText(text, shift);
// Display result
cout << " Given text : " << text << endl;
cout << " Encrypt text : " << encrypt << endl;
return 0;
}
Output
Given text : NEWiceCream
Encrypt text : ZQIuoqOdqmy
// Include namespace system
using System;
/*
Csharp program for
Caesar Cipher
*/
public class CaesarCipher
{
String encryptText(String text, int shift)
{
String output = "";
// Execute loop through by length of given text
for (int i = 0; i < text.Length; ++i)
{
if (text[i] >= 'A' && text[i] <= 'Z')
{
// When character is uppercase letter
output = output + (char)(
(int)((text[i] + shift - 65) % 26) + 65
);
}
else
{
output = output + (char)(
(int)((text[i] + shift - 97) % 26) + 97
);
}
}
return output;
}
public static void Main(String[] args)
{
CaesarCipher task = new CaesarCipher();
String text = "NEWiceCream";
int shift = 12;
String encrypt = task.encryptText(text, shift);
// Display result
Console.WriteLine(" Given text : " + text);
Console.WriteLine(" Encrypt text : " + encrypt);
}
}
Output
Given text : NEWiceCream
Encrypt text : ZQIuoqOdqmy
package main
import "fmt"
/*
Go program for
Caesar Cipher
*/
func encryptText(text string, shift int) string {
var output string = ""
// Execute loop through by length of given text
for i := 0 ; i < len(text) ; i++ {
if text[i] >= 'A' && text[i] <= 'Z' {
// When character is uppercase letter
output = output + string(((int(text[i]) + shift - 65) % 26) + 65)
} else {
output = output + string(((int(text[i]) + shift - 97) % 26) + 97)
}
}
return output
}
func main() {
var text string = "NEWiceCream"
var shift int = 12
var encrypt string = encryptText(text, shift)
// Display result
fmt.Println(" Given text : ", text)
fmt.Println(" Encrypt text : ", encrypt)
}
Output
Given text : NEWiceCream
Encrypt text : ZQIuoqOdqmy
<?php
/*
Php program for
Caesar Cipher
*/
class CaesarCipher
{
function encryptText($text, $shift)
{
$output = "";
// Execute loop through by length of given text
for ($i = 0; $i < strlen($text); ++$i)
{
if ($text[$i] >= 'A' && $text[$i] <= 'Z')
{
// When character is uppercase letter
$output = $output.strval(chr(
((int)((ord($text[$i]) + $shift - 65) % 26) + 65)
));
}
else
{
$output = $output.strval(
chr(
((int)((ord($text[$i]) + $shift - 97) % 26) + 97)
)
);
}
}
return $output;
}
}
function main()
{
$task = new CaesarCipher();
$text = "NEWiceCream";
$shift = 12;
$encrypt = $task->encryptText($text, $shift);
// Display result
echo(" Given text : ".$text.
"\n");
echo(" Encrypt text : ".$encrypt.
"\n");
}
main();
Output
Given text : NEWiceCream
Encrypt text : ZQIuoqOdqmy
/*
Node JS program for
Caesar Cipher
*/
class CaesarCipher
{
encryptText(text, shift)
{
var output = "";
// Execute loop through by length of given text
for (var i = 0; i < text.length; ++i)
{
if (text.charAt(i) >= 'A' && text.charAt(i) <= 'Z')
{
// When character is uppercase letter
output = output + String.fromCharCode(
parseInt((text.charCodeAt(i) + shift - 65) % 26) + 65
);
}
else
{
output = output + String.fromCharCode(
parseInt((text.charCodeAt(i) + shift - 97) % 26) + 97
);
}
}
return output;
}
}
function main()
{
var task = new CaesarCipher();
var text = "NEWiceCream";
var shift = 12;
var encrypt = task.encryptText(text, shift);
// Display result
console.log(" Given text : " + text);
console.log(" Encrypt text : " + encrypt);
}
main();
Output
Given text : NEWiceCream
Encrypt text : ZQIuoqOdqmy
# Python 3 program for
# Caesar Cipher
class CaesarCipher :
def encryptText(self, text, shift) :
output = ""
i = 0
# Execute loop through by length of given text
while (i < len(text)) :
if (text[i] >= 'A'
and text[i] <= 'Z') :
# When character is uppercase letter
output = output + str(chr(
(int)((ord(text[i]) + shift - 65) % 26) + 65
))
else :
output = output + str(chr(
(int)((ord(text[i]) + shift - 97) % 26) + 97
))
i += 1
return output
def main() :
task = CaesarCipher()
text = "NEWiceCream"
shift = 12
encrypt = task.encryptText(text, shift)
# Display result
print(" Given text : ", text)
print(" Encrypt text : ", encrypt)
if __name__ == "__main__": main()
Output
Given text : NEWiceCream
Encrypt text : ZQIuoqOdqmy
# Ruby program for
# Caesar Cipher
class CaesarCipher
def encryptText(text, shift)
output = ""
i = 0
# Execute loop through by length of given text
while (i < text.length)
if (text[i] >= 'A' && text[i] <= 'Z')
# When character is uppercase letter
output = output +(
((text[i].ord + shift - 65) % 26) + 65
).chr.to_s
else
output = output +(
((text[i].ord + shift - 97) % 26) + 97
).chr.to_s
end
i += 1
end
return output
end
end
def main()
task = CaesarCipher.new()
text = "NEWiceCream"
shift = 12
encrypt = task.encryptText(text, shift)
# Display result
print(" Given text : ", text, "\n")
print(" Encrypt text : ", encrypt, "\n")
end
main()
Output
Given text : NEWiceCream
Encrypt text : ZQIuoqOdqmy
import scala.collection.mutable._;
/*
Scala program for
Caesar Cipher
*/
class CaesarCipher()
{
def encryptText(text: String, shift: Int): String = {
var output: String = "";
var i: Int = 0;
// Execute loop through by length of given text
while (i < text.length())
{
if (text.charAt(i) >= 'A' && text.charAt(i) <= 'Z')
{
// When character is uppercase letter
output = output + (
((text.charAt(i).toInt + shift - 65) % 26).toInt
+ 65).toChar.toString();
}
else
{
output = output + (
((text.charAt(i).toInt + shift - 97) % 26).toInt
+
97).toChar.toString();
}
i += 1;
}
return output;
}
}
object Main
{
def main(args: Array[String]): Unit = {
var task: CaesarCipher = new CaesarCipher();
var text: String = "NEWiceCream";
var shift: Int = 12;
var encrypt: String = task.encryptText(text, shift);
// Display result
println(" Given text : " + text);
println(" Encrypt text : " + encrypt);
}
}
Output
Given text : NEWiceCream
Encrypt text : ZQIuoqOdqmy
import Foundation;
/*
Swift 4 program for
Caesar Cipher
*/
class CaesarCipher
{
func encryptText(_ data: String, _ shift: Int) -> String
{
var output: String = "";
var i: Int = 0;
let text = Array(data);
var j = 0;
var k = 0;
// Execute loop through by length of given text
while (i < text.count)
{
j = Int(UnicodeScalar(String(text[i]))!.value);
if (text[i] >= "A" && text[i] <= "Z")
{
// When character is uppercase letter
k = ( (j + shift - 65) % 26 ) + 65 ;
}
else
{
k = ( (j + shift - 97) % 26 ) + 97 ;
}
let s = String(format: "%c", k) as String
output = output + s;
i += 1;
}
return output;
}
}
func main()
{
let task: CaesarCipher = CaesarCipher();
let text: String = "NEWiceCream";
let shift: Int = 12;
let encrypt: String = task.encryptText(text, shift);
// Display result
print(" Given text : ", text);
print(" Encrypt text : ", encrypt);
}
main();
Output
Given text : NEWiceCream
Encrypt text : ZQIuoqOdqmy
/*
Kotlin program for
Caesar Cipher
*/
class CaesarCipher
{
fun encryptText(text: String, shift: Int): String
{
var output: String = "";
var i: Int = 0;
// Execute loop through by length of given text
while (i < text.length)
{
if (text.get(i) >= 'A' && text.get(i) <= 'Z')
{
// When character is uppercase letter
output = output +
(((text.get(i).toInt() + shift - 65) % 26).toInt() +
65).toChar().toString();
}
else
{
output = output +
(((text.get(i).toInt() + shift - 97) % 26).toInt() +
97).toChar().toString();
}
i += 1;
}
return output;
}
}
fun main(args: Array < String > ): Unit
{
val task: CaesarCipher = CaesarCipher();
val text: String = "NEWiceCream";
val shift: Int = 12;
val encrypt: String = task.encryptText(text, shift);
// Display result
println(" Given text : " + text);
println(" Encrypt text : " + encrypt);
}
Output
Given text : NEWiceCream
Encrypt text : ZQIuoqOdqmy
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment