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