c++ 使用bcrypt_如何使用`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

});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值