Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XOR of two hex strings in JavaScript

Tags:

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?

like image 409
thedethfox Avatar asked Dec 13 '13 12:12

thedethfox


People also ask

How do you find the XOR of two hexadecimal numbers?

The XOR is commutative so it starts with the first two hexadecimal numbers, XORs them together, and gets the result. Then it XORs the result with the third hexadecimal and gets the next result.

How to perform XOR in JavaScript?

Unfortunately, JavaScript does not have a logical XOR operator. It has a bitwise XOR operator ^ that can perform a bitwise comparison of two numbers, but this does not help when you want to obtain the result of an XOR of two expressions, that do not return a number.


2 Answers

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.

like image 82
André Pena Avatar answered Oct 09 '22 03:10

André Pena


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

"*)("
like image 21
ajaykools Avatar answered Oct 09 '22 01:10

ajaykools