Reputation: 29
Trying to make a simple encryption/decryption to use it in a simple communication protocol. It seems I can't make my decrypt method to work or maybe is the encryption method, the output text is not the original one. What am I doing wrong?
String s1 = encrypt("Hello World!");
String s2 = decrypt(s1);
public static String encrypt(String decStr) {
byte[] key = new byte[]{
92, -33, 70, 90, 42, -22, -76, 38,
37, 109, 26, -113, 125, 105, 66, 81,
17, 22, 21, -30, 87, -124, -85, 58,
40, -116, -100, 28, 37, 127, 51, 36
};
byte[] encBytes = decStr.getBytes();
int n = encBytes.length + 5;
int k = key[encBytes.length % key.length] & 255;
for (int i = 0; i < encBytes.length; i++) {
encBytes[i] ^= key[(n + i) % key.length];
encBytes[i] ^= key[(k + i) % key.length];
}
return new BigInteger(encBytes).toString(36);
}
public static String decrypt(String encStr) {
byte[] key = new byte[]{
92, -33, 70, 90, 42, -22, -76, 38,
37, 109, 26, -113, 125, 105, 66, 81,
17, 22, 21, -30, 87, -124, -85, 58,
40, -116, -100, 28, 37, 127, 51, 36
};
byte[] encBytes = new BigInteger(encStr, 36).toByteArray();
byte[] decBytes = Arrays.copyOfRange(encBytes, 1, encBytes.length);
int n = decBytes.length + 5;
int k = key[decBytes.length % key.length] & 255;
for (int i = 0; i < decBytes.length; i++) {
decBytes[i] ^= key[(n + i) % key.length];
decBytes[i] ^= key[(k + i) % key.length];
}
return new String(decBytes);
}
Upvotes: 1
Views: 83
Reputation: 498
byte[] decBytes = Arrays.copyOfRange(encBytes, 1, encBytes.length);
You are starting from the second character. Change the 1 to a 0
byte[] decBytes = Arrays.copyOfRange(encBytes, 0, encBytes.length);
Copies the specified range of the specified array into a new array. The initial index of the range (from) must lie between zero and original.length, inclusive. The value at original[from] is placed into the initial element of the copy (unless from == original.length or from == to). Values from subsequent elements in the original array are placed into subsequent elements in the copy. The final index of the range (to), which must be greater than or equal to from, may be greater than original.length, in which case (byte)0 is placed in all elements of the copy whose index is greater than or equal to original.length - from. The length of the returned array will be to - from.
https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#copyOfRange(byte[],%20int,%20int)
Also, you are creating a new byte array and then immediately copying it into a second array but never use the original. It seems there is no need to perform this copy in the first place
Test:
Hello World!
zxj9kxukhtsdmoll41
Hello World!
Upvotes: 2