forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathOneTimePadCipher.java.txt
More file actions
66 lines (59 loc) · 2.01 KB
/
OneTimePadCipher.java.txt
File metadata and controls
66 lines (59 loc) · 2.01 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
package com.thealgorithms.ciphers;
import java.security.SecureRandom;
/**
* Implementation of the One-Time Pad Cipher.
*
* <p>The One-Time Pad Cipher is a symmetric encryption technique that XORs
* plaintext with a truly random key of equal length. It is considered
* theoretically unbreakable when the key is random, used only once, and kept
* secret.
*
* <p>Example:
*
* <pre>
* Plaintext: HELLO
* Key: XMCKL
* Ciphertext: EQNVZ
* </pre>
*
* @see <a href="https://en.wikipedia.org/wiki/One-time_pad">Wikipedia: One-time pad</a>
*/
public final class OneTimePadCipher {
private static final SecureRandom RANDOM = new SecureRandom();
private OneTimePadCipher() {
// Utility class; prevent instantiation.
}
/**
* 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
* @throws IllegalArgumentException if input and key lengths do not match
*/
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();
}
}