The Caesar-Cipher is a monoalphabetic substitution cipher. It is one of the simplest and most used encryption techniques. In this technique, each letter of the given text is replaced by a letter some fixed number of positions down the alphabet.
For example, with a shift of 1, X would be replaced by Y, Y would be replaced by Z and so on. Julius Caesar was the first one who used it for communicating with his officials. Based on his name, this technique was named as Caesar Cipher technique.
An integer value is required to cipher a given text. The integer value is known as ‘shift’, which indicates the number of positions each letter of the text has been moved down.
Write a Java program to input a text and an integer (≥ 1 and ≤ 26) as a shift value. Now encrypt the string and display the encrypted string.
Examples:
INPUT:
Text: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Shift: 23
OUTPUT:
Cipher: XYZABCDEFGHIJKLMNOPQRSTUVW
INPUT:
Text: ATTACKATONCE
Shift: 4
OUTPUT: EXXEGOEXSRGI
import java.util.Scanner;
class Caesar{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Text: ");
String text = in.nextLine();
System.out.print("Shift value: ");
int shift = Integer.parseInt(in.nextLine());
String cipher = "";
if(shift < 1 || shift > 26){
System.out.println("Shift value must be in the range 1 - 26!");
return;
}
for(int i = 0; i < text.length(); i++){
char ch = text.charAt(i);
if(Character.isLetter(ch)){
char base = Character.isUpperCase(ch) ? 'A' : 'a';
cipher += (char)((ch - base + shift) % 26 + base);
}
else
cipher += ch;
}
System.out.println("Cipher: " + cipher);
}
}