故事背景
最近對接了一個第三方支付,冠名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童鞋的傾情演出,轉載請申明地址