SaltHash

SaltHash

SaltHash provides a safe way of storing passwords in the database, by hashing and salting them. This way, database administrators and potential hackers will not be able to reconstruct the password from the salt and hash stored in database. Module is based on bcrypt.

Creating salt and hash

One should not store password as a string by no means. Instead, every password should be hashed and salted before storing. Additionally, every password should be salted with new, completely random salt string (salt should not be reused across entities). Using SaltHash that is pretty straightforward:

SaltHash function expects one argument: password, and returns a hash<string>. Please note that hash includes the salt, so there's no need to store salt separately. For more information check bcrypt.

You can specify salt length as second argument in SaltHash function, default is 9, for optimal performance and security. Increasing the number will make hash harder to exploit, but speed of creating hash dramatically falls.

import { SaltHash } from 'node-mariner';

const password = await SaltHash('userEnteredPassword', 9); // second argument is optional (salt length) defaults to 8
// store the hash in database, eg.
// await User.create({ password, name: 'Test User', email: 'sample@gmail.com' })

SaltHashSync

Sometimes you may want to create a hash synchronously. You can use SaltHashSync function:

import { SaltHashSync } from 'node-mariner';
const hash = SaltHashSync('somepassword', 9); // second argument is optional

Verifying password

To verify password, we provide password user entered, real user password and real user salt (from database) we are comparing against to verifyPassword:

import { verifyPassword } from 'node-mariner';

try {
  const user = await User.findOne({ email: 'sample@gmail.com' })
  await verifyPassword({
    enteredPassword: 'asdfasdf',
    password: user.password,
  });
  // password is correct
} catch (e) {
  // password not correct
}

All keys are mandatory.

Last updated