Caesar Cipher:-
Caesar cipher is one of the earliest known and simplest ciphers. It is a type of replacement cipher in which each letter of the plaintext is ‘moved’ to a certain place under the alphabet.
For example, with a shift of 1, A will be replaced by B, B becomes C, and so on.
The name of this method is named after Julius Caesar, who apparently used it to communicate with his generals.
Caesar Cipher Program in Java
Caesar Cipher Encryption
import java.util.Scanner; public class CaesarCipher { public static void main(String args[]){ String str_message, encrypted_Message = ""; int key; char ch; Scanner scan = new Scanner(System.in); System.out.println("Enter a message to encrypt: "); str_message = scan.nextLine(); System.out.println("Enter the key: "); key = scan.nextInt(); for(int i = 0; i < str_message.length(); ++i){ ch = str_message.charAt(i); if(ch >= 'a' && ch <= 'z'){ ch = (char)(ch + key); if(ch > 'z'){ ch = (char)(ch - 'z' + 'a' - 1); } encrypted_Message += ch; } else if(ch >= 'A' && ch <= 'Z'){ ch = (char)(ch + key); if(ch > 'Z'){ ch = (char)(ch - 'Z' + 'A' - 1); } encrypted_Message += ch; } else { encrypted_Message += ch; } } System.out.println("Encrypted Message is : = " + encrypted_Message); } }
Output:-
Example:- If you run above program then it will ask to enter the message to encrypt like below:-
Enter a message to encrypt:
walmart.com
Enter the key: –for encrypt your message
5
Encrypted Message is : = bfqrfwy.htr
Enter a message to encrypt:
amazon river
Enter the key: –for encrypt your message
5
Encrypted Message is : = frfets wnajw
Caesar Cipher Decryption
import java.util.Scanner; public class CaesarCipher { public static void main(String...s){ String str_message, decrypted_Message = ""; int key; char ch; Scanner scan = new Scanner(System.in); System.out.println("Enter a message to decrypt: "); str_message = scan.nextLine(); System.out.println("Enter key: "); key = scan.nextInt(); for(int i = 0; i < str_message.length(); ++i){ ch = str_message.charAt(i); if(ch >= 'a' && ch <= 'z'){ ch = (char)(ch - key); if(ch < 'a'){ ch = (char)(ch + 'z' - 'a' + 1); } decrypted_Message += ch; } else if(ch >= 'A' && ch <= 'Z'){ ch = (char)(ch - key); if(ch < 'A'){ ch = (char)(ch + 'Z' - 'A' + 1); } decrypted_Message += ch; } else { decrypted_Message += ch; } } System.out.println("Decrypted Message : = " + decrypted_Message); } }
Output:-
Example:- If you run above program then it will ask to enter the message to decrypt like below:-
Enter a message to decrypt:
bfqrfwy.htr
Enter key: –for decrypt your message
5
Decrypted Message : = walmart.com
Enter a message to decrypt:
frfets wnajw
Enter key: –for decrypt your message
5
Decrypted Message : = amazon river