- Published on
Convert MD5 string to integer bits in JavaScript
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 a UUID out of it? Practical real-world use-cases can be - if you have a unique ID that you have in your database which you can map.
This implementation is for JavaScript on the frontend (Javascript, React.js, Vue.js etc.,), we implement the same in the backend using the default crypto module for nodejs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>MD5</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/core.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/md5.js"></script>
<script>
function MD5toUUID(md5Hash) {
return (
md5Hash.substring(0, 8) +
'-' +
md5Hash.substring(8, 12) +
'-' +
md5Hash.substring(12, 16) +
'-' +
md5Hash.substring(16, 20) +
'-' +
md5Hash.substring(20)
).toLowerCase();
}
let digest = "password";
let hash = CryptoJS.MD5(digest);
hash = hash.toString(CryptoJS.enc.Base64);
console.log(MD5toUUID(hash))
</script>
</body>
</html>
In the above code, you can see that we are passing the hash string to the MD5toUUID
function, which returns the UUID value of the md5 hash.
The output of the above code will be a UUID-
5f4dcc3b-5aa7-65d6-1d83-27deb882cf99
I'm glad that you found this article to create UUID from a MD5 hash string useful. Happy Coding.