• 如何使用`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
    });
    

    更多方式可以参考官网

  • 相关阅读:
    阿里Java开发规约【摘录】
    JavaWeb【八、JSP指令与动作元素】
    JavaWeb【七、JSP状态管理】
    JavaWeb【六、JavaBean】
    JavaWeb【五、内置对象】
    JavaWeb【四、JSP基础语法】
    JavaWeb【三、Web程序编写】
    JavaWeb【二、Tomcat安装】
    Django 模板层
    Django auth模块
  • 原文地址:https://www.cnblogs.com/yaogengzhu/p/11028840.html
Copyright © 2020-2023  润新知