简体   繁体   中英

XOR of two hex strings in JavaScript

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?

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 .

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

"*)("

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

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.

If you are on Nodejs, you could transform the hex strings to Buffer s 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');
}

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