How to use the genSalt function from bcryptjs

Find comprehensive JavaScript bcryptjs.genSalt code examples handpicked from public code repositorys.

bcryptjs.genSalt is a method that generates a salt for use in hashing passwords using the bcrypt algorithm.

13
14
15
16
17
18
19
20
21
22
router.put("/:id", async (req, res) => {
  // removed || req.body.isAdmin from the below if statement because it seemed useless because anyone can say they are an admin
  if (req.body.userId === req.params.id) {
    if (req.body.password) {
      try {
        const salt = await bcrypt.genSalt(10);
        req.body.password = await bcrypt.hash(req.body.password, salt);
      } catch (err) {
        return res.status(500).json(err);
      }
fork icon0
star icon3
watch icon1

162
163
164
165
166
167
168
169
170
171
updateUser: async (req, res) => {
	const { id } = req.query;
	const { first_name, last_name, phone } = req.body;
	try {
		// Mã hoá mật khẩu
		// const salt = await bcryptjs.genSalt(saltRounds);
		// const hashedPassword = await bcryptjs.hash(password, salt);
		// Đầu tiên cho so sánh mật khẩu
		const numRows = await User.update(
			// UpdateAt thêm thời gian lúc update
fork icon0
star icon2
watch icon1

+ 2 other calls in file

How does bcryptjs.genSalt work?

bcryptjs.genSalt is a function that generates a salt used for password hashing using bcrypt algorithm, which is a one-way cryptographic function that creates a hash from a password and salt. The salt is randomly generated and is appended to the password to create a secure password hash that can be stored in a database. The salt is important because it adds randomness and complexity to the password hash, making it more difficult for an attacker to reverse engineer the original password. The function takes a number of rounds as an argument which determines the computational cost of hashing, and therefore the security of the resulting hash. The higher the number of rounds, the more secure the hash, but also the longer it takes to generate.

192
193
194
195
196
197
198
199
200
201
    login: req.body.login,
    setor: req.body.setor,
    senha: req.body.senha1,
    eAdmin: true
})
bcrypt.genSalt(10, (erro, salt)=>{
    bcrypt.hash(novoUsuario.senha, salt,(erro,hash)=>{
        if(erro){
            req.flash('error_msg',"Houve um erro ao salvar usuario Administrador")
            res.redirect('/admin/users/add_user')
fork icon0
star icon1
watch icon1

+ 5 other calls in file

52
53
54
55
56
57
58
59
60
61
62
}


async function createUtilisateur(nom,prenom,email,mdp,isAdmin){
    return new Promise((resolve, reject) => {
        //cryptage mdp
        bcrypt.genSalt(10, function (err , salt) {
            if(err) reject(err)
            bcrypt.hash(mdp, salt, function (err, hash) {
                if (err) {
                    console.error('Impossible de crypter le mot de passe')
fork icon0
star icon0
watch icon1

+ 9 other calls in file

Ai Example

1
2
3
4
5
6
7
const bcrypt = require("bcryptjs");

bcrypt.genSalt(10, (err, salt) => {
  bcrypt.hash("myPassword", salt, (err, hash) => {
    console.log(hash);
  });
});

In this example, bcrypt.genSalt() is called with a rounds argument of 10, which determines the complexity of the salt generation process. A higher number of rounds increases the time it takes to generate a salt, which can make it more difficult for attackers to use brute force methods to crack hashed passwords. The second argument to bcrypt.hash() is the salt generated by bcrypt.genSalt(), and the third argument is the password to be hashed. The resulting hash can then be stored in a database or other storage medium for later comparison with user-entered passwords.

825
826
827
828
829
830
831
832
833
834

if (user) {

    jwt.verify(token, process.env.JWT_SECRET_ACCESS_REST_PASS, async (err, user) => {
        if (!err) {
            const salt = await bcrypt.genSalt(10)
            const hashedPassword = await bcrypt.hash(password, salt)
            const refreshToken = generateRefreshToken(id);
            User.findOneAndUpdate({ _id: id }, { password: hashedPassword, refresh: refreshToken }, { upsert: true }, function (err, doc) {
                if (err) return console.log(500, { error: err });
fork icon0
star icon0
watch icon1

64
65
66
67
68
69
70
71
72
73
74
75
userSchema.pre('save', async function (next) {
  // Only run this function is password was actually modified
  if (!this.isModified('password')) return next();


  // Hash the password with cost of 12
  const salt = await bcrypt.genSalt(12);
  this.password = await bcrypt.hash(this.password, salt);


  // Delete passwordConfirm field
  this.passwordConfirm = undefined;
fork icon0
star icon0
watch icon1