Caesar Cipher Algo
Caesar Cipher Technique is the simple and easy method of encryption technique. It is simple type of substitution cipher. Each letter of plain text is replaced by a letter with some fixed number of positions down with alphabet.
package clg.Cypto.assignment;
import java.util.Scanner;
public class CaesarCipher {
// Encrypts text using shift
public static StringBuffer encrypt(String text, int shift) {
StringBuffer result = new StringBuffer();
for (int i = 0; i < text.length(); i++) {
if (Character.isUpperCase(text.charAt(i))) {
char ch = (char) (((int) text.charAt(i) + shift - 65) % 26 + 65);
result.append(ch);
} else {
char ch = (char) (((int) text.charAt(i) + shift - 97) % 26 + 97);
result.append(ch);
}
}
return result;
}
// Decrypts cipher using shift
public static StringBuffer decrypt(String cipher, int shift) {
StringBuffer result = new StringBuffer();
for (int i = 0; i < cipher.length(); i++) {
if (Character.isUpperCase(cipher.charAt(i))) {
char ch = (char) (((int) cipher.charAt(i) + shift - 65) % 26 + 65);
result.append(ch);
} else {
char ch = (char) (((int) cipher.charAt(i) + shift - 97) % 26 + 97);
result.append(ch);
}
}
return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Massager");
String msg = sc.nextLine();
System.out.println("Enter position how many charecter shift");
int k = sc.nextInt();
System.out.println("**********************************************");
System.out.println("Encryption");
System.out.println("Text : " + msg);
System.out.println("Shift : " + k);
String cipher = encrypt(msg, k).toString();
System.out.println("Encrypted Cipher: " + cipher);
System.out.println("Decryption");
System.out.println("Encrypted Cipher: " + cipher);
System.out.println("Shift : " + k);
String decrypted = decrypt(cipher, 26 - k).toString();
System.out.println("Decrypted Plain Text : " + decrypted);
System.out.println("*********************************************");
sc.close();
}
}
=========================================================================
OUTPUT:
Enter Massager
VIKAHSKARMA
Enter position how many charecter shift
3
**********************************************
Encryption
Text : VIKAHSKARMA
Shift : 3
Encrypted Cipher: YLNDKVNDUPD
Decryption
Encrypted Cipher: YLNDKVNDUPD
Shift : 3
Decrypted Plain Text : VIKAHSKARMA
*********************************************
![]() |
| Caesar Cipher |

Comments
Post a Comment