nodejs版本DESede/CBC/PKCS5Padding演算法封裝(3des)

最近對接了一個第三方支付項目,用的加密演算法是沒聽過的:DESede/CBC/PKCS5Padding
乖乖,這個演算法真的是坑爹了,網上搜索了一堆只有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;
};

我們來運行一下



//待加密josn
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+cotWTJ3BtVgmwj2aRWQCwiPfoB1/RKzErV/XFVWwbo00I7F9jpDqO6XxRHGO4yYWlSStS53AbJSSXOZy0Gszlx3MsHVfCLgQJ6uI2Czwn
{"name":"chenqionghe","cn": "雪山飛豬","content": "no pain no gain, light weight baby"}

以上內容為chenqionghe踩坑封裝,感謝lidong童鞋的傾情演出,轉載請申請地址

Tags: