Skip to content

Commit 1e78a3f

Browse files
committed
Add One-Time Pad Cipher implementation (fixed)
1 parent a179b5b commit 1e78a3f

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package com.thealgorithms.ciphers;
2+
3+
import java.security.SecureRandom;
4+
5+
/**
6+
* Implementation of the One-Time Pad Cipher.
7+
*
8+
* <p>The One-Time Pad Cipher is a symmetric encryption technique that XORs
9+
* plaintext with a truly random key of equal length. It is considered
10+
* theoretically unbreakable when the key is random, used only once, and kept
11+
* secret.
12+
*
13+
* <p>Example:
14+
*
15+
* <pre>
16+
* Plaintext: HELLO
17+
* Key: XMCKL
18+
* Ciphertext: EQNVZ
19+
* </pre>
20+
*
21+
* @see <a href="https://en.wikipedia.org/wiki/One-time_pad">Wikipedia: One-time pad</a>
22+
*/
23+
public final class OneTimePadCipher {
24+
25+
private static final SecureRandom RANDOM = new SecureRandom();
26+
27+
private OneTimePadCipher() {
28+
// Utility class; prevent instantiation.
29+
}
30+
31+
/**
32+
* Encrypts or decrypts a message using the One-Time Pad method.
33+
*
34+
* @param input the input string (plaintext or ciphertext)
35+
* @param key the key (must be the same length as input)
36+
* @return the resulting encrypted/decrypted string
37+
* @throws IllegalArgumentException if input and key lengths do not match
38+
*/
39+
public static String xorCipher(String input, String key) {
40+
if (input.length() != key.length()) {
41+
throw new IllegalArgumentException("Input and key lengths must match!");
42+
}
43+
44+
StringBuilder output = new StringBuilder();
45+
for (int i = 0; i < input.length(); i++) {
46+
char encryptedChar = (char) (input.charAt(i) ^ key.charAt(i));
47+
output.append(encryptedChar);
48+
}
49+
return output.toString();
50+
}
51+
52+
/**
53+
* Generates a random key of the same length as the message.
54+
*
55+
* @param length the desired key length
56+
* @return a random key string
57+
*/
58+
public static String generateRandomKey(int length) {
59+
StringBuilder key = new StringBuilder();
60+
for (int i = 0; i < length; i++) {
61+
// Generate printable ASCII range (32–126)
62+
key.append((char) (RANDOM.nextInt(95) + 32));
63+
}
64+
return key.toString();
65+
}
66+
}

0 commit comments

Comments
 (0)