微信小程序用户信息encryptedData详解
程序员文章站
2023-11-13 12:26:28
之前做过一个版本是根据encryptdata和session_key解密得到完整的用户信息(包含union_id)的方法去获取用户信息,由于小程序升级,如今需要废弃encr...
之前做过一个版本是根据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); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。