- Published on
Create MD5 Hash with salt in Javascript
MD5 is (atleast when it was created) a standardized 1-way function that takes in data input of any form and maps it to a fixed-size output string, irrespective of the size of the input string.
Though it is used as a cryptographic hash function, it has been found to suffer from a lot of vulnerabilities.
A salt is a randomly generated string of characters that is used as an additional input to a one-way hash function. Salts are used to protect against dictionary attacks and rainbow table attacks.
The MD5 hash with salt is generated by concatenating the salt to the password and then hashing the resulting string. The salt is then appended to the generated hash to form the complete hash. This complete hash is then stored in the database. When a user attempts to login, the salt is retrieved from the database and used to generate a hash from the provided password. The generated hash is then compared to the hash stored in the database. If the two hashes match, the user is authenticated.
We can create an MD5 hash of a string in JavaScript without using an hash as well. In this article we will create a hash by using a salt.
If you are looking to generate md5 checksum in nodejs, please follow this article - Creating MD5 Hash with salt in Node.js.
The method below is for creating it at client-side or browser.
Using CryptoJS MD5 hash with salt
Here we will be using the above npm package directly in HTML code. We are using version 4.1.1
of the crypto-js
package. Let's use the Cloudflare CDN links and use <script>
tags to import core.min.js
and md5.js
scripts.
After that, you can use it in your code as CryptoJS.MD5(yourString)
. Here is an example demonstrating crypto-js
and md5
implementation-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>SHA256</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>
let digest = "password"
let salt = "80zzm081sr@nd0m"
let algo = CryptoJS.algo.MD5.create()
algo.update(digest, "utf-8")
algo.update(CryptoJS.MD5(salt), "utf-8")
hash = algo.finalize().toString(CryptoJS.enc.hex)
console.log(hash)
</script>
</body>
</html>
Output of the above code is going to be an alert with value 0ea24bf69b2a0d1e252feef08e3116e5
.
NOTE: Please do not use this to hash passwords and store it in your databases, prefer SHA-256 or SHA-512 or other superior cryptographic hash functions for the same.
I'm glad that you found the content useful. Happy Coding.