XOR of two hex strings in JavaScript

Viewed 15161
var hex1 = "B1C85C061C98E713DEF0E2EDDDDB432738674C9F8962F09B75E943D55F9FB39F";
var hex2 = "121B0D3327A21B8048FC7CA6FD07AACC0D8DF59B99DB098686696573E3686E6C";

var result = hex1 ^ hex2; //XOR the values

console.log(result); // outputs: 0 which does not sound good.

Any ideas how to perform XOR operations on hex values?

5 Answers

If you are on Nodejs, you could transform the hex strings to Buffers then use map to build the resulting string.

function xor(hex1, hex2) {
  const buf1 = Buffer.from(hex1, 'hex');
  const buf2 = Buffer.from(hex2, 'hex');
  const bufResult = buf1.map((b, i) => b ^ buf2[i]);
  return bufResult.toString('hex');
}

Below is function that takes in 2 strings like "041234FFFFFFFFFF" and "0000000709000003" (a classic example of pin block and card block) Expected result from the above 2 strings is "041234F8F6FFFFFC"

function bitwiseXorHexString(pinBlock1, pinBlock2) {
  var result = ''
  for (let index = 0; index < 16; index++) {
    const temp = (parseInt(pinBlock1.charAt(index), 16) ^ parseInt(pinBlock2.charAt(index), 16)).toString(16).toUpperCase()
    result += temp
  }
  return result
}

Note: This was made to xor 2 strings of fixed length 16. You may modify it as per your needs.

Related