2
2
3
3
import java .nio .charset .Charset ;
4
4
import java .nio .charset .StandardCharsets ;
5
- import java .util .Base64 ;
5
+ import java .util .HexFormat ;
6
6
7
7
/**
8
8
* A simple implementation of XOR cipher that, given a key, allows to encrypt and decrypt a plaintext.
@@ -17,23 +17,25 @@ public final class XORCipher {
17
17
private XORCipher () {
18
18
}
19
19
20
- private static byte [] xor (final byte [] inputBytes , final byte [] keyBytes ) {
20
+ public static byte [] xor (final byte [] inputBytes , final byte [] keyBytes ) {
21
21
byte [] outputBytes = new byte [inputBytes .length ];
22
22
for (int i = 0 ; i < inputBytes .length ; ++i ) {
23
23
outputBytes [i ] = (byte ) (inputBytes [i ] ^ keyBytes [i % keyBytes .length ]);
24
24
}
25
25
return outputBytes ;
26
26
}
27
27
28
- public static String encrypt (final String plaintext , final String key ) {
29
- byte [] plaintextBytes = plaintext .getBytes (CS_DEFAULT );
28
+ public static String encrypt (final String plainText , final String key ) {
29
+ byte [] plainTextBytes = plainText .getBytes (CS_DEFAULT );
30
30
byte [] keyBytes = key .getBytes (CS_DEFAULT );
31
- return Base64 .getEncoder ().encodeToString (xor (plaintextBytes , keyBytes ));
31
+ byte [] xorResult = xor (plainTextBytes , keyBytes );
32
+ return HexFormat .of ().formatHex (xorResult );
32
33
}
33
34
34
- public static String decrypt (final String cipher , final String key ) {
35
- byte [] cipherBytes = Base64 . getDecoder ().decode ( cipher );
35
+ public static String decrypt (final String cipherText , final String key ) {
36
+ byte [] cipherBytes = HexFormat . of ().parseHex ( cipherText );
36
37
byte [] keyBytes = key .getBytes (CS_DEFAULT );
37
- return new String (xor (cipherBytes , keyBytes ), CS_DEFAULT );
38
+ byte [] xorResult = xor (cipherBytes , keyBytes );
39
+ return new String (xorResult , CS_DEFAULT );
38
40
}
39
41
}
0 commit comments