之前做過一個版本是根據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();}
解密的算法
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); }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答