如何使用`bcrypt`方式加密


如何使用bcrypt方式加密

我在以前都是使用的md5的方式進行密碼加密,由於md5存在一定的風險,而且這個這個依賴已經很久沒有更新了,故本次采用的是bcrypt方式加密。

使用方式

useage(command)

  • 下包 npm i bcrypt
const bcrypt = require('bcrypt');
const saltRounds = 10;
const myPlaintextPassword = 's0/\/\P4$$w0rD';
const someOtherPlaintextPassword = 'not_bacon';

to hash a password

如何加密密碼

//方式1:
bcrypt.genSalt(saltRounds, function(err, salt) {
    bcrypt.hash(myPlaintextPassword, salt, function(err, hash) {
        // Store hash in your password DB.
    });
});
//方式2 
bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) {
  // Store hash in your password DB.
});

以上兩種方式都可以達到相同的加密結果

如何校驗密碼

to check password

// Load hash from your password DB.
bcrypt.compare(myPlaintextPassword, hash, function(err, res) {
    // 密碼正確,會返回的res為true
    // res == true
});
bcrypt.compare(someOtherPlaintextPassword, hash, function(err, res) {
    // 密碼不對,則返回的res 為false
    // res == false
});

值得注意的是:“比較”功能可以對抗定時攻擊(使用所謂的“恆定時間”算法)。通常,如果密碼,加密密鑰或加密哈希與安全性相關,則不要使用常規JavaScript字符串比較函數來比較密碼,加密密鑰或加密哈希值。

除了使用以上方式,還可以使用promise方式進行加密

bcrypt使用global.Promise中可用的任何Promise實現。 NodeJS> = 0.12內置了一個本機Promise實現。但是,這應該適用於任何Promises / A +兼容的實現。

接受回調的異步方法,如果Promise支持可用,則在未指定回調時返回Promise。

useage

bcrypt.hash(myPlaintextPassword, saltRounds).then(function(hash) {
    // Store hash in your password DB.
});

使用promise方式驗證密碼是否一致

// Load hash from your password DB.
// myPlaintextPassword 為密碼, hash為加密后的密碼
bcrypt.compare(myPlaintextPassword, hash).then(function(res) {
    // res == true
});
bcrypt.compare(someOtherPlaintextPassword, hash).then(function(res) {
    // res == false
});

更多方式可以參考官網


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM