I am trying to convert BigInteger numbers to its hex format so that I could use it for further HMAC calculations. I have used the following post for getting the code to do this.
Converting a 64 bit number string to word array using CryptoJS
The code works perfectly fine for positive BigInteger Numbers but doesn't produce the correct results when used for negative BigInteger Numbers.
For example: Consider the code piece below from the linked post:
function intToWords(num, lengthInBytes) {
var bigInt = new BigInteger();
bigInt.fromString(num, 10); // radix is 10
var hexNum = bigInt.toString(16); // radix is 16
if (lengthInBytes && lengthInBytes * 2 >= hexNum.length) {
hexNum = Array(lengthInBytes * 2 - hexNum.length + 1).join("0") + hexNum;
}
return CryptoJS.enc.Hex.parse(hexNum);
}
I passed the num value as -52 and lengthInBytes value as 8. The hexNum(third line of the intToWords function) generated is "-34" (instead of being "ffffffffffffffcc")
Could someone help me to correctly convert the input number to its right Hex format?
I figured this one out. The library was returning the right hex value. I just had to get the 2's compliment of the hex number(line 3).