Ceaser Cipher Java Implementation
The Caesar cipher, also known as a shift cipher, is one of the simplest forms of encryption. It is a substitution cipher where each letter in the original message (called the plaintext) is replaced with a letter corresponding to a certain number of letters up or down in the alphabet.
In this way, a message that initially was quite readable, ends up in a form that can not be understood at a simple glance.
For example, here's the Caesar Cipher encryption of a message, using a right shift of 3.
Plaintext:
THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
Ciphertext:
QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD
Encryption: c=(m+k)mod 26
Decryption: m=(c-k+26)mod 26
source code:
package ceaser;
import java.util.Scanner;
public class Ceaser {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter the plaintext:");
Scanner in =new Scanner(System.in);
String str=in.nextLine();
Ceaser.encryption(str);
System.out.println("Enter the ciphertext:");
str=in.nextLine();
Ceaser.decryption(str);
}
public static void encryption(String str){
String en="";
for(int i=0;i<str.length();i++){
char ch = (char) (((int)str.charAt(i) +3 - 97) % 26 + 97);
en +=ch;
}
System.out.println("The ciphertext is:"+en);
}
public static void decryption(String str){
String en="";
for(int i=0;i<str.length();i++){
char ch = (char) (((int)str.charAt(i) -3 +26 -97) % 26 + 97);
en +=ch;
}
System.out.println("The ciphertext is:"+en);
}
}
Output:
Enter the plaintext:
patancampus
The ciphertext is:sdwdqfdpsxv
Enter the ciphertext:
ghimireshankar
The ciphertext is:defjfobpexkhxo
No comments:
Post a Comment