Search code examples
javacryptographyxorcbc-mode

Cipher Block Chaining: XOR implementation in Java


How you implement the XOR from CBC (Cipher Block Chaining) in Java? I know how to do it when both of my values are booleans, but what do I do if I have numbers instead of booleans?

For Example:

i1 = 15
i2 = 4

How do I XOR i1 and i2?


Solution

  • Java has a bitwise XOR operator build in, see the Java Language Specification. The XOR works on all primitive integral types (i.e. types that directly represent numbers for you and me): byte, short, int, long and char. This XOR operator will do a bitwise XOR of the bits at identical positions, and then output the result. There is also the ^= which will store the result back in the left hand variable.

    Now it depends on your implementation of CBC if you would do this on bytes or on 32 bit integers (int). Normally you would use bytes, but if you've implemented AES using 32 bit constructs you would use integers. Integers would be slightly faster, but the time that XOR takes will pale in comparison with the block cipher operation anyway.

    So you can simply have a for loop (up to the block size in bytes) and XOR each and every byte of the last ciphertext with the next plaintext during encryption or the last ciphertext with the result - after decryption - of the next ciphertext during decryption.


    You may need to cast back to a byte when using the XOR operation on two byte values, as Java automatically upcasts the operands - and therefore the result - to 32 bit integers (int):

    byte x = 0b0011; // 0b indicates a binary literal
    byte y = 0b0101; 
    byte r = (byte) (x ^ y); // results in 0b0110 or the value 6 in decimals
    

    Bytes are signed values in Java, meaning that you may get negative values. That's OK though, you can simply ignore this as long as you just use bitwise operations. It's only of importance during mathematical operations such as addition or multiplication.