Java解密微信小程序开放数据

大数据
后台-插件-广告管理-内容页头部广告(手机)

微信官方文档:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html

下面是微信官方介绍的界面方法,但是通过下载代码示例包后发现,没有Java版的解密示例,可能微信没有Java程序员吧。

微信官方推荐的界面算法

参考微信官方提供的Python版解密示例,我们来实现Java版的数据解密

import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import java.util.Base64;import javax.crypto.Cipher;import javax.crypto.spec.IvParameterSpec;import javax.crypto.spec.SecretKeySpec;public class WXBizDataCrypt {    private String appId;    private String sessionKey;    public WXBizDataCrypt(String appId, String sessionKey) {        this.appId = appId;        this.sessionKey = sessionKey;    }    public JSONObject decrypt(String encryptedData, String iv) throws Exception {        byte[] sessionKeyBytes = Base64.getDecoder().decode(sessionKey);        byte[] encryptedDataBytes = Base64.getDecoder().decode(encryptedData);        byte[] ivBytes = Base64.getDecoder().decode(iv);        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");        SecretKeySpec keySpec = new SecretKeySpec(sessionKeyBytes, "AES");        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);        byte[] decryptedBytes = cipher.doFinal(encryptedDataBytes);        String decryptedString = new String(decryptedBytes, "UTF-8");        JSONObject decryptedJson = JSON.parseObject(decryptedString);        if (!decryptedJson.getJSONObject("watermark").getString("appid").equals(appId)) {            throw new Exception("Invalid Buffer");        }        return decryptedJson;    }    public static void main(String[] args) throws Exception {        String encryptedData = "xxx";        String iv = "xxxxx";        String session_key = "xxx";        String appid = "xxxx";        WXBizDataCrypt crypt = new WXBizDataCrypt(appid, session_key);        JSONObject decrypt = crypt.decrypt(encryptedData, iv);        System.out.println(decrypt);    }

执行main方法即可完成对微信加密数据的解密了

下面介绍一下加密数据的获取方式:

  • appid:注册微信小程序,在设置-账户信息中查看
  • encryptedData和iv:通过微信wx.getUserProfile 接口获取
  • session_key:需要通过wx.login接口获取code,再调用微信的jscode2session接口获取,调用方法参考官方文档:https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html
后台-插件-广告管理-内容页尾部广告(手机)
标签:

评论留言

我要留言

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。