18
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?

Golo Roden
  • 140,679
  • 96
  • 298
  • 425
thedethfox
  • 1,651
  • 2
  • 20
  • 38

5 Answers5

13

Bitwise operations in JavaScript only work on numeric values.

You should parseInt(hexString, 16) your hex string before. Specifically in your case this wouldn't work because your hex is too big for a number. You would have to create your own customized XOR function.

Take a look at this link: How to convert hex string into a bytes array, and a bytes array in the hex string?

The resulting bytearray will be ellegible for a manual XOR. Byte by byte. Maybe this will help: Java XOR over two arrays.

Andre Pena
  • 56,650
  • 48
  • 196
  • 243
9

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');
}
secure12
  • 153
  • 1
  • 6
5
str = 'abc';
c = '';
key = 'K';
for(i=0; i<str.length; i++) {
    c += String.fromCharCode(str[i].charCodeAt(0).toString(10) ^ key.charCodeAt(0).toString(10)); // XORing with letter 'K'
}
return c;

Output of string 'abc':

"*)("
ajaykools
  • 645
  • 7
  • 12
3

You can use a function like this.

function xor(a, b) {
  if (!Buffer.isBuffer(a)) a = new Buffer(a)
  if (!Buffer.isBuffer(b)) b = new Buffer(b)
  var res = []
  if (a.length > b.length) {
    for (var i = 0; i < b.length; i++) {
       res.push(a[i] ^ b[i])
    }
 } else {
 for (var i = 0; i < a.length; i++) {
   res.push(a[i] ^ b[i])
   }
 }
 return new Buffer(res);
}

Source: https://github.com/czzarr/node-bitwise-xor

1

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.

varun kalra
  • 213
  • 2
  • 7