Aerodynamika
Aerodynamika

Reputation: 8413

How to perform password reset in Node.Js app using hash?

I want to implement password reset in my Node.Js app using a very good advice from here https://stackoverflow.com/a/27580553/712347 where I would not have to record any tokens into my database.

Instead @airtonix suggested to use a hash function based on the user's login, email, password, timestamp, secret and salt.

What I don't understand is how do hash functions actually work — let's say I get a certain sequence from the data above — what would be the algorithm (and the library) to use to check if it was generated from the same data using a different salt?

Or am I misunderstanding the whole thing?

Upvotes: 0

Views: 547

Answers (1)

Blake Basas
Blake Basas

Reputation: 89

How do Hash functions generally actually work -

Hash Algorithms create a digital fingerprint of data usually called Digest or Hash. You primarily see Hash Algorithms used for comparison purposes rather than encryption.

Secure Hash Algorithms have some fundamental characteristics such as:

  • Non-reversible (one way function). You cannot determine the original set of data from the Digest.
  • The Digest will be a fixed size regardless of the original data's size.
  • Unique. Two different data sets cannot produce the same Digest.

What would be the algorithm and the library to use?

I would recommend SHA-2 (SHA-256 or SHA-512) as the hashing algorithm and utilize the Crypto module. It provides cryptographic functionality and a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions.

So lets say we have the following information (user.id, user.email, user.password, timestamp), concatenate it and pass it as the data parameter.

const hash = function hash(data){

   // Returns a buffer containing raw bytes and converts to string
   const salt = crypto.randomBytes(128).toString('base64')

   // Creates and returns a Hmac object that uses the given algorithm
   const hmac = crypto.createHmac('sha512', salt)

   // Updates the Hmac object content with the given data
   hmac.update(data)

   // Calculates the digest of all of the data passed to be hashed
   const digest = hmac.digest('hex')

   return {
     'salt'  : salt,
     'digest': digest
   } 

}

Running the above function with the same data but a different salt would result in a completely different Digest.

Upvotes: 3

Related Questions