1、小程序登录授权,前端需要传入的参数:
code==登录授权的
rawData==计算签名使用
encryptedData==包括敏感数据在内的完整用户信息的加密数据
iv == 加密算法的初始向量
signature == 字符串[sha1(rawData+sessionkey)]
2、根据传入的参数进行加解密
String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appId+"&secret="+secret+"&js_code="+authLoginReq.code+"&grant_type=authorization_code"
RestTemplate restTemplate = new RestTemplate()
ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class)
WxUser wx = new WxUser()
if(responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK){
String sessionData = responseEntity.getBody()
logger.info("sessionData = "+ sessionData)
JSONObject jsonObj = JSON.parseObject(sessionData)
String openId = jsonObj.getString("openid")
String sessionKey = jsonObj.getString("session_key")
logger.info("openId = "+ openId+"||sessionKey:"+sessionKey)
String signature = HmacUtil.SHA1(authLoginReq.rawData+sessionKey)
if(!signature.equals(authLoginReq.signature)){
logger.info("req signature="+authLoginReq.getSignature()+"||"+" java signature="+authLoginReq.getSignature())
}
byte[] resultByte = null
Base64Url base64Url = new Base64Url()
try {
resultByte = decrypt(base64Url.base64UrlDecode(authLoginReq.encryptedData), base64Url.base64UrlDecode(sessionKey), base64Url.base64UrlDecode(authLoginReq.getIv()))
} catch (Exception e){
logger.error("数据异常:"+e)
}
if(null != resultByte && resultByte.length > 0){
String userInfoStr = ""
try {
userInfoStr = new String(resultByte, "UTF-8")
}catch (UnsupportedEncodingException e){
logger.error(e.getMessage())
}
logger.info("userInfo返回 = "+ userInfoStr)
//{"openId":"oH1yH5J3Medgyr44EdPAYcxvrVCI","nickName":"小何&电话й15900844809","gender":1,"language":"zh_CN","city":"Yichun","province":"Jiangxi","country":"China","avatarUrl":"https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKvtG0bAIJaK2ibsttXsFjjMoR5Nf7gCG0mLqpAXGckVjico6tNJ8KaibbN2qm8X9SOz1dLRnqleYPAw/132","watermark":{"timestamp":1543371577,"appid":"wxf964790ef2cc3120"}}
JSONObject userInfoObj = JSON.parseObject(userInfoStr)
wx.openId= openId
wx.sex = userInfoObj.getString("gender") as Integer
wx.nickname = userInfoObj.getString("nickName")
wx.city = userInfoObj.getString("city")
wx.province = userInfoObj.getString("province")
wx.country = userInfoObj.getString("country")
wx.headImgUrl = userInfoObj.getString("avatarUrl")
加解密算法:
/**
* 小程序解密方法
* @param content
* @param keyByte
* @param ivByte
* @return
* @throws InvalidAlgorithmParameterException
*/
private byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte) throws InvalidAlgorithmParameterException {
initialize();
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
Key sKeySpec = new SecretKeySpec(keyByte, "AES");
cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(ivByte));// 初始化
byte[] result = cipher.doFinal(content);
return result;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void initialize(){
if (initialized) return;
Security.addProvider(new BouncyCastleProvider());
initialized = true;
}
//生成iv
public static AlgorithmParameters generateIV(byte[] iv) throws Exception{
AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
params.init(new IvParameterSpec(iv));
return params;
}
算法:
class HmacUtil {
public static boolean initialized = false
public static String SHA1(String str){
try {
//指定sha1算法
MessageDigest digest = MessageDigest.getInstance("SHA-1")
digest.update(str.getBytes())
//获取字节数组
byte[] messageDigest = digest.digest()
// Create Hex String
StringBuffer hexString = new StringBuffer()
// 字节数组转换为 十六进制 数
for (int i = 0; i < messageDigest.length; i++) {
String shaHex = Integer.toHexString(messageDigest[i] & 0xFF)
if (shaHex.length() < 2) {
hexString.append(0)
}
hexString.append(shaHex)
}
return hexString.toString().toLowerCase()
} catch (NoSuchAlgorithmException e) {
return ""
}
}
}