修改 web-server 接口加解密逻辑

This commit is contained in:
liangtongchuan
2022-03-14 20:22:22 +08:00
parent ce53f2bd96
commit 8a6627ea13

View File

@@ -3,6 +3,10 @@ import { genCode } from 'app/pubUtils/util';
import { Context } from 'egg';
const crypto = require('crypto');
const isJSON = require('koa-is-json');
import fs = require('fs');
import path = require('path');
const privateKey = fs.readFileSync(path.resolve(__dirname, `../resource/privateKey`));
function aesEncrypt(data, key, iv) {
const cipher = crypto.createCipheriv('aes-192-cbc', key, iv);
@@ -18,6 +22,14 @@ function aesDecrypt(data, key, iv) {
return decrypted;
}
function privateDecrypt(encryptMsg) {
const decryptMsg = crypto.privateDecrypt(
privateKey,
encryptMsg
);
return decryptMsg;
}
module.exports = options => {
return async function parmsDecode(ctx: Context, next) {
let url = ctx.request.url;
@@ -29,8 +41,13 @@ module.exports = options => {
if (options.threshold && ctx.length < options.threshold) return;
const reqBody = ctx.request.body;
const reqHeader = ctx.request.header;
const aesKey = reqHeader['k'] ? privateDecrypt(Buffer.from(reqHeader['k'], 'base64')) : ENCRYPT_KEY;
const aesIV = reqHeader['v'] ? privateDecrypt(Buffer.from(reqHeader['v'], 'base64')) : ENCRYPT_IV;
if (isJSON(reqBody)) {
const encodeStr = aesEncrypt(JSON.stringify(reqBody), ENCRYPT_KEY, ENCRYPT_IV);
const encodeStr = aesEncrypt(JSON.stringify(reqBody), aesKey, aesIV);
console.log(`encoded str: ${encodeStr}`);
}
@@ -43,7 +60,7 @@ module.exports = options => {
if (!reqBody.data) return;
const decodeStr = aesDecrypt(reqBody.data, ENCRYPT_KEY, ENCRYPT_IV);
const decodeStr = aesDecrypt(reqBody.data, aesKey, aesIV);
ctx.logger.debug('decoded str:', decodeStr);
try {
ctx.request.body = JSON.parse(decodeStr);
@@ -64,10 +81,10 @@ module.exports = options => {
const resBody = ctx.body;
console.log('return value:', JSON.stringify(resBody));
if (isJSON(resBody)) {
ctx.body = { result: aesEncrypt(JSON.stringify(resBody), ENCRYPT_KEY, ENCRYPT_IV) };
ctx.body = { result: aesEncrypt(JSON.stringify(resBody), aesKey, aesIV) };
ctx.service.utils.log('INFO', `[${ctx.request.url}] [${ctx.logcode}] res: ${JSON.stringify(resBody)}`)
} else {
ctx.body = { result: aesEncrypt(JSON.stringify({ status: 3, data: 'internal err' }), ENCRYPT_KEY, ENCRYPT_IV) };
ctx.body = { result: aesEncrypt(JSON.stringify({ status: 3, data: 'internal err' }), aesKey, aesIV) };
ctx.service.utils.log('ERROR', `[${ctx.request.url}] [${ctx.logcode}] res: ${resBody}`)
}
};