微信小程序接口安全优化(AES加密)

接口优化

优化前:http://a.com/message.php?page=0

优化后:

http://a.com/message.php?page=参数&openid=用户唯一标识&t=时间戳&sign=密文

举个例子:

http://127.0.0.1:808/xiaomi_new/feishu/AES/cs.php?page=11&openid=ou_xxxx

&t=1668575721&sign=eed5d9829f56ee7bf26ec96f2ef1e637

sign的计算方法:

MD5(AES({"page":"11","openid":"ou_xxxx","t":"1668575721"}))

AES加密方法为AES-128-ECB

  • page => 翻页参数
  • openid => 用户唯一标识码
  • t => 时间戳 //参考时钟为RPC(北京建立基准时钟) 精度到秒
  • sign => 密文

后端验签流程

  1. 判断t时间戳是否在30s以内。(防止重放)
  2. 判断openid是否未正确并且用户登录日期是否和当前日期匹配。(防止openid盗用)
  3. 获取到page&openid&t&ip后进行加密,密文和sign进行对比。(防止篡改)

POC:http://a.com/message.php?page=2&openid=ou_xxxx&t=1667986784472&sign=密文

实现代码:

将参数首先进行AES-128-ECB加密,在外层在进行md5加密。

1、建立utils文件夹,存放aes.js、md5.js及aes_util.js工具类。

(1)引入CryptoJS ,将CryptoJS 存入aes.js中。

                CryptoJS 官方地址https://github.com/sytelus/CryptoJS

              直接复制地址:点击链接 CrytoJS文件

(2)引入 md5 加密,点击链接 javascript md5加密               

(3)封装aes加密方法

const CryptoJS = require('./aes'); //引用AES源码js
const utilMd5 = require('./md5');
const key = CryptoJS.enc.Utf8.parse('密钥');
const iv = CryptoJS.enc.Utf8.parse('1234567812345678');
// aes ecb加密方法
function AesEncryptECB(word) {
  let srcs = CryptoJS.enc.Utf8.parse(word);
  let encrypted = CryptoJS.AES.encrypt(srcs, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  // md5加密
  return utilMd5.hexMD5(encrypted.toString());
}
module.exports = {
  AesEncryptECB
}

2、使用ase加密接口

// 引入
const CryptoJS = require('../..//utils/aes_util') //获取加密组件
  // 获取创意信息
  getDataList() {
    let that = this;
    let timestamp = Date.parse(new Date()) / 1000;
    const data = {
      page: that.data.page.toString(),
      t: timestamp,
      openid: that.data.openId
    }
    // 调用秘钥方法
    let sign = CryptoJS.AesEncryptECB(JSON.stringify(data))
    wx.request({
      url: 'http://xxxxxxxxxxx',
      data: { ...data, sign },
      method: 'GET',
      header: {
        'content-type': 'application/xml'
      },
      success: function (res) {
        let resData = res.data.data;
        console.log(resData)
      },
      fail: function (err) {
        console.log(err)
      },
    })
  },

猜你喜欢

转载自blog.csdn.net/TongJ_/article/details/128429258
今日推荐