Reputation: 15
I have a problem in trying to XOR 4 different byte arrays. From what I understand about XOR, A XOR B = C; B XOR C = A.
public static byte[] test(byte[] b1, byte[] b2, byte[] b3, byte[] b4) {
if (b1.length > b2.length) {
byte[] tmp = b2;
b2 = b1;
b1 = tmp;
}
for (int i = 0; i < b1.length; i++) {
b2[i] ^= b1[i];
}
if (b2.length > b3.length) {
byte[] tmp = b3;
b3 = b2;
b2 = tmp;
}
for (int i = 0; i < b2.length; i++) {
b3[i] ^= b2[i];
}
if (b3.length > b4.length) {
byte[] tmp = b4;
b4 = b3;
b3 = tmp;
}
for (int i = 0; i < b3.length; i++) {
b4[i] ^= b3[i];
}
return b4;
}
I have 4 byte arrays: b1, b2, b3, b4. I used the above method to give me a byte array we shall call b5.
Now let's say to get b1, we would use b2, b3, b4, b5 as parameters in the above method. However, this would not return me b1.
So I would like to know if there's a problem with the code or if it's due to my lack of understanding of XOR operations.
Upvotes: 1
Views: 781
Reputation: 533570
To XOR the bytes of any number of arrays like this.
public static byte[] xor(byte[]... arrays) {
int len = 0;
for (byte[] array : arrays)
len = Math.max(len, array.length);
byte[] result = new byte[len];
for (int i = 0; i < len; i++) {
byte b = 0;
for (byte[] array : arrays)
b ^= i < array.length ? array[i] : 0;
result[i] = b;
}
return result;
}
NOTE: To avoid confusion, I have created a new array and returned that, rather than return the longest byte[].
Upvotes: 0
Reputation: 11903
How I would do it:
byte[] xor(byte[] a, byte[] b) {
if (a.length != b.length) throw new IllegalArgumentException();
byte[] c = new byte[a.length];
for (int i = 0; i < a.length; i++) {
c[i] = a[i] ^ b[i];
}
return c;
}
Then you can test it:
byte[] b1 = ..., b2 = ... b3 = ..., b4 = ...;
byte[] b5 = xor(b1, xor(b2, xor(b3, b4)));
Upvotes: 2
Reputation: 43748
This has nothing to do with XOR, but you are overwriting your arrays when you calculate it. The content after calling the method is not the same as before. Furthermore, your result array is one of the input arrays. This causes all kinds of aliasing problems.
Upvotes: 3