DEV Community

Cover image for Compare Hash Passwords Using Crypto Module using the Node.js [part 2]
Ugbem Job
Ugbem Job

Posted on

Compare Hash Passwords Using Crypto Module using the Node.js [part 2]

This article is a continuation of my previous article on Hash Passwords Using Crypto Module using Node.js. This aims at teaching you how to convert crypto hash passwords into their original form using the Crypto Module.

In the previous article, we discussed how to hash passwords using the Crypto module in Node.js. In this article, we'll be discussing how to compare the hashed password with the original password.

From the previous article, we created a simple function that takes a password as input and returns its hashed version. Let's use this function to hash a password and store it in a variable.

const crypto = require('crypto')
const hashPassword = password => {
    return crypto.createHash('sha256').update(password).digest('hex')
}
const password = hashPassword('secret')
console.log(password)
Enter fullscreen mode Exit fullscreen mode

Compare Hash Passwords Using Crypto Module using the Node.js

const hashedPassword = '2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b'

// Compare the hashed password with the original password


const compareHashPassword = (password, hashedPassword) => {
    if (hashPassword(password) === hashedPassword) {
        return { success: true, message: 'Password matched' }
    }
    return { success: false, message: 'Password not matched' }
}

const result = compareHashPassword('secret', hashedPassword)
console.log(result)

// Output
// { success: true, message: 'Password matched' }
Enter fullscreen mode Exit fullscreen mode

In this article, we discussed how to compare the hashed password with the original password using the Crypto module in Node.js.

Note: This article is a continuation of my previous article on Hash Passwords Using Crypto Module using Node.js. This aims at teaching you how to convert crypto hash passwords into their original form using the Crypto Module and it is important to note that this is just a basic example of how to compare hashed passwords in a Node.js application using the crypto module.

You can find the previous article on Hash Passwords Using Crypto Module using the Node.js here.

If you enjoyed this article, you might also like:

Top comments (1)

Collapse
 
edwinluijten profile image
Edwin Luijten

The way you are comparing the hashes is insecure, based on the time it takes the attacker can construct a valid hash.

The longer it takes the more valid the hash is. en.wikipedia.org/wiki/Timing_attack

For hashes you need a timing safe comparison (constant time comparison). The crypto library has a function for this: crypto.timingSafeEqual(a, b).

nodejs.org/api/crypto.html