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童鞋的倾情演出,转载请申明地址

  • 相关阅读:
    一个word小技巧
    Android 自定义组件之 带有悬浮header的listview
    传智播客 java基础 相关资料 Day2
    js取整 摘抄
    ifram子页面父页面相互调用
    寻知图项目收获--项目管理方面
    圣经学习 读经群读经记录(一)申命记5-7章
    java1234教程系列笔记 S1 Java SE chapter 02 写乘法口诀表
    java1234教程系列笔记 S1 Java SE chapter 02 lesson 03 java基本数据类型
    java1234教程系列笔记 S1 Java SE 02 eclipse初步使用、注释、标识符
  • 原文地址:https://www.cnblogs.com/chenqionghe/p/13501374.html
Copyright © 2011-2022 走看看