1

I want to encrypt user password and save encrypted password in database. which encryption algorithm should i use ? what is the best way to use crypto in nodejs for encryption/decryption process ?

jww
  • 97,681
  • 90
  • 411
  • 885
  • Possible duplicate of [SALT and HASH password in nodejs w/ crypto](https://stackoverflow.com/questions/17201450/salt-and-hash-password-in-nodejs-w-crypto) – Jacob H May 02 '18 at 18:38
  • This is both opinion-based and too broad as asked. There are any number of ways to do this--pick one (but please don't do your own crypto). – Dave Newton May 02 '18 at 18:40
  • 1
    You want to hash passwords, not encrypt them. Use bcrypt, or if that is not available, PBKDF2. – Luke Joshua Park May 02 '18 at 22:28
  • @LukeJoshuaPark : thanks, hashing is right technique in case of storing password – Saurav Singh May 03 '18 at 17:11

1 Answers1

1

Here's a very basic implemenation to give you an idea, please look at what it does and read the crypto documenation on nodejs.org.

import { pbkdf2Sync, randomBytes } from 'crypto';

export class PasswordHash {
  private iters = 1e1; // TODO: increase later
  private keylen = 64;
  private digest = 'sha512';

  create(password) {
    const salt = randomBytes(128).toString('base64');

    const hash = pbkdf2Sync(password, salt, this.iters, this.keylen, this.digest).toString('base64');

    return [salt, hash, this.iters].join('::');
  }

  verify(stored, password) {
    const [salt, hash, iters] = stored.split('::');
    const verify = pbkdf2Sync(password, salt, parseInt(iters, 10), this.keylen, this.digest);

    return hash === verify.toString('base64');
  }
}
martin8768
  • 565
  • 5
  • 20