Nodejs - Mã hóa mật khẩu

Mã hóa mật khẩu người dùng trước khi lưu vào database là 1 chuyện bắt buộc phải làm đối với bất cứ 1 website nào. Không riêng gì ai, Nodejs cũng hỗ trợ khá nhiều thư viện để hỗ trợ việc mã hóa này.

Ảnh: http://websitedesign.schoolsict.co.uk

bcrypt.js

Bcrypt được sử dụng khá nhiều, ban đầu được thiết kế bởi Niels Provos và David Mazières, xem thêm thông tin tại wikipedia.

Cài đặt

npm install bcrypt

Cách sử dụng

Để mã hóa mật khẩu

var bcrypt = require('bcrypt');
bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash('B4c0/\/', salt, function(err, hash) {
        // Store hash in your password DB.
    });
});

Để kiểm tra mật khẩu:

// Load hash from your password DB.
bcrypt.compare('B4c0/\/', hash, function(err, res) {
    // res == true
});
bcrypt.compare('not_bacon', hash, function(err, res) {
    // res == false
});

Auto-gen a salt and hash:

bcrypt.hash('bacon', 8, function(err, hash) {
});

sync

Để mã hóa mật khẩu:

var bcrypt = require('bcrypt');
var salt = bcrypt.genSaltSync(10);
var hash = bcrypt.hashSync('B4c0/\/', salt);
// Store hash in your password DB.

Để kiểm tra mật khẩu:

// Load hash from your password DB.
bcrypt.compareSync('B4c0/\/', hash); // true
bcrypt.compareSync('not_bacon', hash); // false

Auto-gen a salt and hash:

var hash = bcrypt.hashSync('bacon', 8);
JavascriptNodejsTutorialbcrypt