Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

小程序添加解密加密数据方法。 #134

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/api_common.js
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ class API {
err.code = 40001;
throw err;
}
return this.getAccessToken();
throw new Error('can\'t set access token');
}
}

Expand Down
28 changes: 28 additions & 0 deletions lib/util.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
'use strict';
const crypto = require('crypto');

/*!
* 对提交参数一层封装,当POST JSON,并且结果也为JSON时使用 */
Expand Down Expand Up @@ -42,3 +43,30 @@ function _replaceOneChar(c) {
exports.replaceJSONCtlChars = function (str) {
return str.replace(JSONCtlCharsRE, _replaceOneChar);
};

/**
* 小程序加密数据解密算法
* https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html
* @param {string} sessionKey
* @param {string} iv
* @param {string} encryptedData
* @returns {Object}
*/
exports.decryptDataForMiniProgram = function (sessionKey, iv, encryptedData) {
const sessionKeyBuffer = Buffer.from(sessionKey, 'base64');
const ivBuffer = Buffer.from(iv, 'base64');
const encryptedBuffer = Buffer.from(encryptedData, 'base64');

try {
const decipher = crypto.createDecipheriv('aes-128-cbc', sessionKeyBuffer, ivBuffer);
// 设置自动 padding 为 true,删除填充补位
decipher.setAutoPadding(true);
const decoded =
decipher.update(encryptedBuffer, 'binary', 'utf8') +
decipher.final('utf8');

return JSON.parse(decoded);
} catch (err) {
throw new Error('解密失败');
}
};
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "co-wechat-api",
"name": "co-wechat-api-new",
"version": "3.11.0",
"description": "微信公共平台Node库API,ES6版本",
"main": "index.js",
Expand Down Expand Up @@ -30,7 +30,7 @@
"rewire": "*",
"travis-cov": "*"
},
"author": "Jackson Tian",
"author": "Salamander",
"license": "MIT",
"readmeFilename": "README.md",
"directories": {
Expand Down