import java.util.Scanner;
public class CaesarCipher {
// Method to encrypt text using Caesar Cipher
public static String encrypt(String text, int shift) {
StringBuilder encrypted = new StringBuilder();
for (char character : text.toCharArray()) {
if (Character.isLetter(character)) {
char base = Character.isUpperCase(character) ? 'A' : 'a';
char newChar = (char) ((character - base + shift) % 26 + base);
encrypted.append(newChar);
} else {
encrypted.append(character); // Keep non-alphabetic characters as is
}
}
return encrypted.toString();
}
// Method to decrypt text using Caesar Cipher
public static String decrypt(String text, int shift) {
return encrypt(text, 26 - (shift % 26)); // Reversing the shift
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the text:");
String text = scanner.nextLine();
System.out.println("Enter the shift value:");
int shift = scanner.nextInt();
// Encrypt the text
String encryptedText = encrypt(text, shift);
System.out.println("Encrypted Text: " + encryptedText);
// Decrypt the text
String decryptedText = decrypt(encryptedText, shift);
System.out.println("Decrypted Text: " + decryptedText);
scanner.close();
}
}
No comments:
Post a Comment