zoukankan      html  css  js  c++  java
  • nodejs版本DESede/CBC/PKCS5Padding算法封装(3des)

    故事背景

    最近对接了一个第三方支付,冠名PKU的支付项目,用的加密算法是:DESede/CBC/PKCS5Padding
    其实就是类似AES/DES的对称加密,这个算法真的是坑爹了,网上搜索了一堆只有java版本是正常的,nodejs版本的各种问题,我了个乖乖,硬着头皮调了大半天,踩了N个坑,真的是无语了。talk is cheap,上代码!

    核心代码

    const crypto = require('crypto');
    
    /**
     * base64编码
     * @param text
     * @returns {Buffer}
     */
    function base64(text) {
        return Buffer.from(text, "base64");
    };
    
    /**
     * 加密
     *
     * @param text
     * @param secretKey
     * @returns {string}
     */
    function encode(text, secretKey) {
        secretKey = base64(secretKey);
        const cipher = crypto.createCipheriv('des-ede3-cbc', secretKey, Buffer.alloc(8));
        const encrypted = cipher.update(text, 'utf8', 'base64');
    
        return encrypted + cipher.final('base64');
    };
    
    
    /**
     * 解密
     * @param encryptedBase64
     * @param secretKey
     * @returns {string}
     */
    function decode(encryptedBase64, secretKey) {
        secretKey = base64(secretKey);
        const decipher = crypto.createDecipheriv('des-ede3-cbc', secretKey, Buffer.alloc(8));
        let decrypted = decipher.update(encryptedBase64, 'base64', 'utf8');
        decrypted += decipher.final('utf8');
        return decrypted;
    };
    

    运行结果

    我们来运行一下

    //待加密内容
    let json = `{"name":"chenqionghe","cn":"雪山飞猪","content":"no pain no gain, light weight baby"}`;
    //密钥
    let key = 'mdgIaBrQjIKU30IIEpZS1dsFNOLX73nQ';
    //加密
    let encrypted = encode(json, key);
    console.log(encrypted);
    //解密
    console.log(decode(encrypted, key));
    

    输出

    EPvugsT71sqeIDPuVuP0mx+cotWTJ3Bt+k5vIConcQmdyjIgF3GtQLSL+yCyxTfRQIjBFmkq7bQn6Nh0xOjMSm3C23AM1m3QwZLFQHH2t41X/4YyvCnv3YFtgDu+SosO
    {"name":"chenqionghe","cn":"雪山飞猪","content":"no pain no gain, light weight baby"}
    

    以上内容为chenqionghe踩坑封装,感谢lidong童鞋的倾情演出,转载请申明地址

  • 相关阅读:
    区分JS的空值
    死锁
    高效的SQLSERVER分页方案
    IIS经典模式VS集成模式
    MVC过滤器
    Request接收参数乱码原理解析
    int三种转化区别
    Area使用
    Action和Partial等区别
    Log4Net
  • 原文地址:https://www.cnblogs.com/chenqionghe/p/13501374.html
Copyright © 2011-2022 走看看