Untitled
unknown
plain_text
2 months ago
2.0 kB
3
Indexable
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class CaesarCipher { static Scanner sc = new Scanner(System.in); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public static void main(String[] args) throws IOException { System.out.print("Enter any String: "); String str = br.readLine(); System.out.print("\nEnter the Key: "); int key = sc.nextInt(); // Normalize the key to handle large or negative values key = key % 26; String encrypted = encrypt(str, key); System.out.println("\nEncrypted String is: " + encrypted); String decrypted = decrypt(encrypted, key); System.out.println("\nDecrypted String is: " + decrypted); } public static String encrypt(String str, int key) { StringBuilder encrypted = new StringBuilder(); for (int i = 0; i < str.length(); i++) { char currentChar = str.charAt(i); if (Character.isUpperCase(currentChar)) { currentChar = (char) ((currentChar + key - 'A') % 26 + 'A'); } else if (Character.isLowerCase(currentChar)) { currentChar = (char) ((currentChar + key - 'a') % 26 + 'a'); } encrypted.append(currentChar); } return encrypted.toString(); } public static String decrypt(String str, int key) { StringBuilder decrypted = new StringBuilder(); for (int i = 0; i < str.length(); i++) { char currentChar = str.charAt(i); if (Character.isUpperCase(currentChar)) { currentChar = (char) ((currentChar - key - 'A' + 26) % 26 + 'A'); } else if (Character.isLowerCase(currentChar)) { currentChar = (char) ((currentChar - key - 'a' + 26) % 26 + 'a'); } decrypted.append(currentChar); } return decrypted.toString(); } }
Editor is loading...
Leave a Comment