Convert MD5 string to integer in Node.js
As we've seen in earlier posts, you can create an MD5 hash of a string and generate a hash in string type. But, what if you had to create an integer out of it? Practical real-world use-cases can be - if you have a unique integer ID that you have in your database which you can map.
This implementation is for Node.js and server-side frameworks like Expressjs. In case you are looking for a JavaScript on the frontend (Javascript, React.js, Vue.js etc.,), implementation using CryptoJS module for JavaScript.
Here we will use the BigInt.asIntN()
to convert the MD5 hash string to integer of base 16.
const bigInt = BigInt(`0x${hash.substring(0, 16)}`);
const signed64 = BigInt.asIntN(64, bigInt);
The above code is used to create a BigInt representation of a hash stored as a hexadecimal string. This code takes a bigInt value and returns it as an intN value. The intN value is 64 bits long and is a signed representation of the value bigInt
.
The base of the integer defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal.
import { createHash } from "crypto";
const yourString = "password";
const hash = createHash("md5").update(yourString).digest("hex");
const bigInt = BigInt(`0x${hash.substring(0, 16)}`);
const signed64 = BigInt.asIntN(64, bigInt);
console.log(signed64);
The output of the above code will be an integer value-
6867369562105931222n
Optionally, you can strip off the last character n
by doing signed64.slice(0, -1)
or a.slice(0, signed64.length-1)
. So, the final code will look something like-
import { createHash } from "crypto";
const yourString = "password";
const hash = createHash("md5").update(yourString).digest("hex");
const bigInt = BigInt(`0x${hash.substring(0, 16)}`);
const signed64 = BigInt.asIntN(64, bigInt);
const finalInt = signed64.slice(0, -1);
console.log(finalInt);
The output of the above code will be an integer value-
6867369562105931222
I'm glad that you found this article to convert MD5 hash value to int useful. Happy Coding.