之前做过一个版本是根据encryptData和Session_key解密得到完整的用户信息(包含union_id)的方法去获取用户信息,由于小程序升级,如今需要废弃encryptData的方式去获取用户信息,改成使用encryptedData的方式获取用户信息。
新的数据解密方法
接口如果涉及敏感数据(如wx.getUserInfo当中的 openId 和unionId ),接口的明文内容将不包含这些敏感数据。开发者如需要获取敏感数据,需要对接口返回的加密数据( encryptedData )进行对称解密。 解密算法如下:
对称解密使用的算法为 AES-128-CBC,数据采用PKCS#7填充。
对称解密的目标密文为 Base64_Decode(encryptedData),
对称解密秘钥 aeskey = Base64_Decode(session_key), aeskey 是16字节
对称解密算法初始向量 iv 会在数据接口中返回。
微信官方提供了多种编程语言的示例代码。每种语言类型的接口名字均一致。调用方式可以参照示例。
另外,为了应用能校验数据的有效性,我们会在敏感数据加上数据水印( watermark )
{
"openId": "OPENID",
"nickName": "NICKNAME",
"gender": GENDER,
"city": "CITY",
"province": "PROVINCE",
"country": "COUNTRY",
"avatarUrl": "AVATARURL",
"unionId": "UNIONID",
"watermark":
{
"appid":"APPID",
"timestamp":TIMESTAMP
}
}
总的来说还是原来的算法,还是原来的逻辑结构,不同的是解密方式,以前是通过session_key得到iv,现如今是直接从前台接口处得到iv来解密,所改变的也只是传输的数据
@RequestMapping(value = "/web/wechatapp/jscode2session", method = RequestMethod.POST)
@ResponseBody
public String getSessionByCode(@RequestBody String jsonStr, HttpServletRequest request) {
JSONObject jsonObj = JSONObject.fromObject(jsonStr)
String code = (String) jsonObj.get("code")
JSONObject wechatAppUserInfo = jsonObj.getJSONObject("wechatAppUserInfo")
String encryptedData = (String) wechatAppUserInfo.get("encryptedData")
String iv = (String) wechatAppUserInfo.get("iv")
WechatUserInfo wechatUserInfo = wechatAppManager.doOAuth(code, encryptedData, iv)
if (wechatUserInfo == null) {
throw new BusinessException(BusinessException.Code.WECHAT_OAUTH_ERROR, "微信小程序授权失败!!!")
}
HttpSession session = request.getSession(true)
User user = wechatUserInfo.getUser()
logger.debug("微信小程序用户 union id: {}, 对应车车用户{}", wechatUserInfo.getUnionid(), user.getId())
session.setAttribute(WebConstants.SESSION_KEY_USER, CacheUtil.doJacksonSerialize(user))
ClientTypeUtil.cacheClientType(request, ClientType.WE_CHAT_APP)
return session.getId()
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
解密的算法
public static byte[] decrypt(String dataStr,String keyStr, String ivStr) throws Exception{
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider())
byte[] encryptedData = Base64.decode(dataStr)
byte[] keyBytes = Base64.decode(keyStr)
AlgorithmParameters iv = WechatAppDecryptor.generateIV(Base64.decode(ivStr))
Key key = convertToKey(keyBytes)
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM)
//设置为解密模式
cipher.init(Cipher.DECRYPT_MODE, key,iv)
return cipher.doFinal(encryptedData)
}