|
| 1 | +package com.thealgorithms.ciphers; |
| 2 | + |
| 3 | +import java.security.SecureRandom; |
| 4 | + |
| 5 | +/** |
| 6 | + * The One-Time Pad Cipher is a symmetric encryption technique |
| 7 | + * that XORs plaintext with a truly random key of equal length. |
| 8 | + * |
| 9 | + * ⚠️ Important: |
| 10 | + * - The key must be random and used only once. |
| 11 | + * - Key reuse makes it insecure. |
| 12 | + * |
| 13 | + * Example: |
| 14 | + * Plaintext: HELLO |
| 15 | + * Key: XMCKL |
| 16 | + * Ciphertext: EQNVZ |
| 17 | + * |
| 18 | + * Reference: |
| 19 | + * Shannon, C. E. (1949). Communication Theory of Secrecy Systems. |
| 20 | + */ |
| 21 | +public class OneTimePadCipher { |
| 22 | + |
| 23 | + private static final SecureRandom RANDOM = new SecureRandom(); |
| 24 | + |
| 25 | + /** |
| 26 | + * Encrypts or decrypts a message using the One-Time Pad method. |
| 27 | + * |
| 28 | + * @param input The input string (plaintext or ciphertext) |
| 29 | + * @param key The key (must be the same length as input) |
| 30 | + * @return The resulting encrypted/decrypted string |
| 31 | + */ |
| 32 | + public static String xorCipher(String input, String key) { |
| 33 | + if (input.length() != key.length()) { |
| 34 | + throw new IllegalArgumentException("Input and key lengths must match!"); |
| 35 | + } |
| 36 | + |
| 37 | + StringBuilder output = new StringBuilder(); |
| 38 | + for (int i = 0; i < input.length(); i++) { |
| 39 | + char encryptedChar = (char) (input.charAt(i) ^ key.charAt(i)); |
| 40 | + output.append(encryptedChar); |
| 41 | + } |
| 42 | + return output.toString(); |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * Generates a random key of the same length as the message. |
| 47 | + * |
| 48 | + * @param length The desired key length |
| 49 | + * @return A random key string |
| 50 | + */ |
| 51 | + public static String generateRandomKey(int length) { |
| 52 | + StringBuilder key = new StringBuilder(); |
| 53 | + for (int i = 0; i < length; i++) { |
| 54 | + // Generate printable ASCII range (32–126) |
| 55 | + key.append((char) (RANDOM.nextInt(95) + 32)); |
| 56 | + } |
| 57 | + return key.toString(); |
| 58 | + } |
| 59 | + |
| 60 | + public static void main(String[] args) { |
| 61 | + String message = "HELLO WORLD"; |
| 62 | + String key = generateRandomKey(message.length()); |
| 63 | + |
| 64 | + String encrypted = xorCipher(message, key); |
| 65 | + String decrypted = xorCipher(encrypted, key); |
| 66 | + |
| 67 | + System.out.println("Message: " + message); |
| 68 | + System.out.println("Key: " + key); |
| 69 | + System.out.println("Encrypted: " + encrypted); |
| 70 | + System.out.println("Decrypted: " + decrypted); |
| 71 | + } |
| 72 | +} |
0 commit comments