简体   繁体   中英

How to XOR two byte arrays of different length

I have two byte[ ] variables of different length which I would use to XOR to give me the third variable. Let's call them b1 and b2 , and the third variable b3 .

Using this third variable, I can:

  1. b3 XOR b2 to give me b1 .
  2. b3 XOR b1 to give me b2 .

However, I have a problem with getting back the values of b1 and b2 as they are not of the same length.

public static byte[] xor(byte[] b1, byte[] b2) {
    byte[] oneAndTwo = new byte[Math.min(b1.length, b2.length)];
    for (int i = 0; i < oneAndTwo.length; i++) {
        oneAndTwo[i] = (byte) (((int) b1[i]) ^ ((int) b2[i]));
    }
    return oneAndTwo;
}

public static void main(String[] args) throws UnsupportedEncodingException {
    byte[] b1 = "Hi".getBytes("UTF-8");
    byte[] b2 = "Hello".getBytes("UTF-8");
    byte[] b3 = XORTest.xor(b1, b2);

    byte[] mb1 = XORTest.xor(b2, b3);
    byte[] mb2 = XORTest.xor(b1, b3);

    System.out.println(Arrays.equals(b1, mb1));   //prints true
    System.out.println(new String(mb1, "UTF-8")); //prints "Hi"

    System.out.println(Arrays.equals(b2, mb2));   //prints false
    System.out.println(new String(mb2, "UTF-8")); //prints "He"
}

So I would like to know if there's a way to perform XOR on two byte[ ] of different length.

One solution is to take the maximum length so no information is lost, but assume that trailing 0 bytes should be truncated.

public static byte[] xor(byte[] b1, byte[] b2) {
    byte[] oneAndTwo = new byte[Math.max(b1.length, b2.length)];
    for (int i = 0; i < b1.length && i < b2.length; i++)
        oneAndTwo[i] = (byte) (b1[i] ^ b2[i]);
    for (int i = b2.length; i < b1.length; i++)
        oneAndTwo[i] = b1[i];
    for (int i = b1.length; i < b2.length; i++)
        oneAndTwo[i] = b2[i];
    int length = oneAndTwo.length;
    while (length > 0 && oneAndTwo[length - 1] == 0)
        length--;
    if (length < oneAndTwo.length)
        return Arrays.copyOf(oneAndTwo, length);
    return oneAndTwo;
}

public static void main(String[] args) {
    byte[] b1 = "Hi".getBytes(StandardCharsets.UTF_8);
    byte[] b2 = "Hello".getBytes(StandardCharsets.UTF_8);
    byte[] b3 = xor(b1, b2);

    byte[] mb1 = xor(b2, b3);
    byte[] mb2 = xor(b1, b3);

    System.out.println(Arrays.equals(b1, mb1));  
    System.out.println(new String(mb1, StandardCharsets.UTF_8));

    System.out.println(Arrays.equals(b2, mb2));   
    System.out.println(new String(mb2, StandardCharsets.UTF_8));
}

prints

true
Hi
true
Hello

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM