node 加密解密模块_Node(十二)加密解密

token:(引入jsonwebtoken模块)

对称加密,一个秘钥进行加密解密

const crypto = require('crypto');

// 产生token

let obj = {

a: 1,

b: 2,

};

let sec = 'HelloWorld'

let res = jwt.sign(obj, sec,{ algorithm: 'RS256'});//传入加密的对象,秘钥,加密方式

console.log(res);

//解析token

let sec2 = jwt.verify('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoxLCJiIjoyLCJpYXQiOjE1NDM5ODA0NTF9.ORMQa_LBbDCd7XEEHgVGN2EnccL2kTOyDidE-b4ANMY', sec);

console.log(sec2);

非对称加密,通过私钥进行加密,公钥解密

产生私钥 openssl genrsa -out private_key.pem 1024

由私钥产生公钥 openssl rsa -in private_key.pem -pubout -out public_key.pem

var selfkey = fs.readFileSync(path.join(__dirname, 'key.pem'));//读取私钥路径

var jwtset = jwt.sign({

a: 1,

b: 2,

c: 3

}, selfkey, {

algorithm: 'RS256'

});

console.log(jwtset);

var otherkey = fs.readFileSync(path.join(__dirname, 'public_key.pem'));//读取公钥路径

var jwtget = jwt.verify(jwtset, otherkey, {

algorithm: 'RS256'

});

console.log(jwtget);

crypto和bcrypt

// 数据库密码加密

// 内置crypto

// MD5

const hash = crypto.createHash('md5');

hash.update('HelloWorld');

console.log(hash.digest('hex'));

// Hmac

const hmac = crypto.createHmac('sha256', '12345');

hmac.update('HelloWorld');

console.log(hmac.digest('hex'));

// 第三方bcrypt

const pass = 'qazwsx123';

const saltRounds = 10;

bcrypt.genSalt(saltRounds, (err, salt) => {

bcrypt.hash(pass, salt, (err, hash) => {

let result= bcrypt.compareSync('qazwsx123', hash);

console.log(result);

});

});

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值