前言:微信敏感数据需要加解密
- 小程序调用wx.login() 获取 临时登录凭证code ,并回传到开发者服务器。
- 开发者服务器以code换取 用户唯一标识openid 和 会话密钥session_key。
- 获取code->获取session_key
调用wx.login(),获取code,通过自建服务器,向微信服务器请求获取session_key,例:
https://api.weixin.qq.com/sns/jscode2session?appid=固定的appid&secret=固定的secret&js_code=每次小程序传参&grant_type=authorization_code
返回
{"session_key":"xxxxxxxxxxxxxx==","expires_in":7200,"openid":"xxxxxxxxxxxx"}
- 利用session_key和encryptedData、iv解密手机号,encryptedData、iv通过小程序点击获取登录用户手机授权取得,例:
<button class='loginBtn' open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">登录/注册</button>
(注:open-type 必须是 "getPhoneNumber",否则无效 )
返回
{errMsg: "getPhoneNumber:ok", encryptedData: "zCxufhXc6MsvM5EPgFTUmPWcLRQZJEf+/YQQJPpxo8+GwJSX0Z…PNKqtXRiPSkBTtZWpc1ViCySaWrhlRMwjT0KARIPm7hh/dg==", iv: "xyR8amjJ6RKC8pjRFFv9HA=="}
自建服务器解密代码:
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.AlgorithmParameterSpec;
/**
* 小程序AES解密
*/
public class AESDecodeUtils {
public static void main(String[] args) throws Exception {
byte[] encryptedData = Base64.decodeBase64("通过小程序授权获取到的encryptedData");
byte[] ivData = Base64.decodeBase64("通过小程序授权获取到的iv");
byte[] session_key = Base64.decodeBase64("通过自建服务器请求微信后台获取到的session_key");
System.out.println(decrypt(session_key,ivData,encryptedData));
}
public static String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception {
AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
//解析解密后的字符串
return new String(cipher.doFinal(encData),"UTF-8");
}
}
解密后,得到的数据:
{
"phoneNumber": "13812341234", //号码是假的(国外手机号会有区号)
"purePhoneNumber": "13812341234",
"countryCode": "86",
"watermark":
{
"appid":"APPID",
"timestamp":TIMESTAMP
}
}
加密数据解密算法
微信对于权限管理和安全性做得还是挺到位的