|
8 | 8 | * A simple implementation of XOR cipher that, given a key, allows to encrypt and decrypt a plaintext.
|
9 | 9 | *
|
10 | 10 | * @author <a href="https://github.com/lcsjunior">lcsjunior</a>
|
11 |
| - * |
| 11 | + * |
12 | 12 | */
|
13 | 13 | public class XORCipher {
|
14 | 14 |
|
15 |
| - private static final Charset CS_DEFAULT = StandardCharsets.UTF_8; |
16 |
| - |
17 |
| - private XORCipher() { |
18 |
| - } |
19 |
| - |
20 |
| - private static byte[] xor(final byte[] inputBytes, final byte[] keyBytes) { |
21 |
| - byte[] outputBytes = new byte[inputBytes.length]; |
22 |
| - for (int i = 0; i < inputBytes.length; ++i) { |
23 |
| - outputBytes[i] = (byte) (inputBytes[i] ^ keyBytes[i % keyBytes.length]); |
24 |
| - } |
25 |
| - return outputBytes; |
26 |
| - } |
27 |
| - |
28 |
| - public static String encrypt(final String plaintext, final String key) { |
29 |
| - byte[] plaintextBytes = plaintext.getBytes(CS_DEFAULT); |
30 |
| - byte[] keyBytes = key.getBytes(CS_DEFAULT); |
31 |
| - return Base64.getEncoder().encodeToString(xor(plaintextBytes, keyBytes)); |
32 |
| - } |
33 |
| - |
34 |
| - public static String decrypt(final String cipher, final String key) { |
35 |
| - byte[] cipherBytes = Base64.getDecoder().decode(cipher); |
36 |
| - byte[] keyBytes = key.getBytes(CS_DEFAULT); |
37 |
| - return new String(xor(cipherBytes, keyBytes), CS_DEFAULT); |
38 |
| - } |
39 |
| - |
| 15 | + private static final Charset CS_DEFAULT = StandardCharsets.UTF_8; |
| 16 | + |
| 17 | + private XORCipher() { |
| 18 | + } |
| 19 | + |
| 20 | + private static byte[] xor(final byte[] inputBytes, final byte[] keyBytes) { |
| 21 | + byte[] outputBytes = new byte[inputBytes.length]; |
| 22 | + for (int i = 0; i < inputBytes.length; ++i) { |
| 23 | + outputBytes[i] = (byte) (inputBytes[i] ^ keyBytes[i % keyBytes.length]); |
| 24 | + } |
| 25 | + return outputBytes; |
| 26 | + } |
| 27 | + |
| 28 | + public static String encrypt(final String plaintext, final String key) { |
| 29 | + byte[] plaintextBytes = plaintext.getBytes(CS_DEFAULT); |
| 30 | + byte[] keyBytes = key.getBytes(CS_DEFAULT); |
| 31 | + return Base64.getEncoder().encodeToString(xor(plaintextBytes, keyBytes)); |
| 32 | + } |
| 33 | + |
| 34 | + public static String decrypt(final String cipher, final String key) { |
| 35 | + byte[] cipherBytes = Base64.getDecoder().decode(cipher); |
| 36 | + byte[] keyBytes = key.getBytes(CS_DEFAULT); |
| 37 | + return new String(xor(cipherBytes, keyBytes), CS_DEFAULT); |
| 38 | + } |
40 | 39 | }
|
0 commit comments