forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOneTimePadCipher.java
More file actions
39 lines (30 loc) · 1.15 KB
/
OneTimePadCipher.java
File metadata and controls
39 lines (30 loc) · 1.15 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
package com.thealgorithms.ciphers;
import java.security.SecureRandom;
import java.util.Objects;
public final class OneTimePadCipher {
private static final SecureRandom RANDOM = new SecureRandom();
private OneTimePadCipher() {}
public static byte[] generateKey(final int length) {
if (length <= 0) {
throw new IllegalArgumentException("Key length must be positive");
}
byte[] key = new byte[length];
RANDOM.nextBytes(key);
return key;
}
public static byte[] encrypt(final byte[] plaintext, final byte[] key) {
Objects.requireNonNull(plaintext, "plaintext");
Objects.requireNonNull(key, "key");
if (plaintext.length != key.length) {
throw new IllegalArgumentException("Plaintext and key must have the same length");
}
byte[] ciphertext = new byte[plaintext.length];
for (int i = 0; i < plaintext.length; i++) {
ciphertext[i] = (byte) (plaintext[i] ^ key[i]);
}
return ciphertext;
}
public static byte[] decrypt(final byte[] ciphertext, final byte[] key) {
return encrypt(ciphertext, key);
}
}