how to salt a password in typescript

To salt a password in TypeScript, we can use the bcrypt library which provides a method to generate a salted hash of the password. Here's an example of how to do it:

index.ts
import bcrypt from 'bcrypt';

const saltRounds = 10;
const plainPassword = 'mySuperSecretPassword';

// Generate a salt
bcrypt.genSalt(saltRounds, (err, salt) => {
  if (err) {
    console.error(err);
    return;
  }

  // Hash the password with the salt
  bcrypt.hash(plainPassword, salt, (err, hash) => {
    if (err) {
      console.error(err);
      return;
    }

    // Store the hash in the database
    console.log(hash);
  });
});
440 chars
24 lines

In this example, the genSalt method is used to generate a salt with a cost factor of 10 (which determines the computational complexity of the hashing). Then the hash method is used to generate a salted hash of the plainPassword. The salt is automatically added to the hash and can be stored in the database.

Using bcrypt to hash and salt passwords is a secure method for password storage and is recommended for any application using user authentication.

gistlibby LogSnag