XOR of two hex strings in JavaScript

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');
}

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':

"*)("

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.

Tags:

Javascript