zoukankan      html  css  js  c++  java
  • 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);
        });
    });
  • 相关阅读:
    Java基础知识
    spring data jpa 表关联设置用户表关联角色表配置
    centos 服务器 nginx 负载均衡服务安装
    Java jdk 8 新特性
    个人收款支付系统-半自动化解决方案
    纯净版Windows7系统迅雷下载路径
    Centos里开机自启动Node 服务程序
    Centos 7将java jar包自定义开机启动服务
    安装zabbix-agent客户端
    Centos7系统安装Zabbix4.4(yum源安装)
  • 原文地址:https://www.cnblogs.com/HelloWorld-Yu/p/10193683.html
Copyright © 2011-2022 走看看