java实现⼩程序获取并解密⽤户数据(前台+后台)⼀、概述
推出了⼩程序,很多公司的客户端应⽤不仅具有了APP、H5、还接⼊了⼩程序开发。但是,⼩程序中竟然没有提供Java版本的加密数据解密算法。这着实让⼴⼤的Java开发⼈员蛋疼。
⼆、实⼩程序端的实现(⼩程序app.js)
doLogin(scene) {
wx.showLoading({
title: '加载中...',
})
var _this = this;
wx.login({
success: function (loginRes) {
if (loginRes) {
//获取⽤户信息
success: function (infoRes) {
console.log('===开始request请求');
//请求服务端的登录接⼝
url: _this.globalData.url + '/v1/api/login',
data: {
code: de,//临时登录凭证
rawData: infoRes.rawData,//⽤户⾮敏感信息
signature: infoRes.signature,//签名
encrypteData: ptedData,//⽤户敏感信息
iv: infoRes.iv,//解密算法的向量
scene: _this.globalData.scene
},
success: function (res) {
res = res.data;
wx.hideLoading();
if (de == 1) {
console.log('登录成功!');
wx.setStorageSync('userInfo', res.data);
wx.navigateBack({
delta: -1
});
} else {
console.log('登录失败!');
}
},
fail: function (error) {
//调⽤服务端登录接⼝失败
console.log(error);
}
});
}
});
} else {
}
}
});
}
三、实现Java版本的⼩程序加密数据解密算法
package ller.wx;
import java.io.UnsupportedEncodingException;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.spec.InvalidParameterSpecException;
import java.util.Arrays;
import java.util.Map;
pto.BadPaddingException;
pto.Cipher;
pto.IllegalBlockSizeException;
pto.NoSuchPaddingException;
pto.spec.IvParameterSpec;
pto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
dehaus.xfire.util.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import ity.User;
import com.api.service.UserService;
import com.api.utils.Constant;
js获取json的key和valueimport com.api.utils.HttpSenderUtil;
import com.api.utils.Result;
import com.api.utils.StringUtils;
@RequestMapping("/v1/api")
@Controller
public class WxLoginController {
@Autowired
private UserService userService;
@RequestMapping("/login")
@ResponseBody
public Result<Map<String,Object>> doLogin(Model model,
@RequestParam(value = "code",required = false) String code,
@RequestParam(value = "rawData",required = false) String rawData,
@RequestParam(value = "signature",required = false) String signature,
@RequestParam(value = "encrypteData",required = false) String encrypteData, @RequestParam(value = "iv",required = false) String iv,
@RequestParam(value = "scene",required = false) String scene){
//System.out.println("⽤户⾮敏感信息"+rawData);
JSONObject rawDataJson = JSON.parseObject( rawData );
//System.out.println("签名"+signature);
JSONObject SessionKeyOpenId = getSessionKeyOrOpenId( code );
//System.out.println("SessionAndopenId="+SessionKeyOpenId);
String openId = String("openid" );
String sessionKey = String( "session_key" );
//System.out.println("openid="+openId+",session_key="+sessionKey);
Map<String,Object> mapUser = userService.findByOpenid(openId);
User user = new User();
if(mapUser==null){
String nickName = String( "nickName" );
String avatarUrl = String( "avatarUrl" );
String gender = String( "gender" );
String city = String( "city" );
String country = String( "country" );
String province = String( "province" );
user.setOpenId(openId);
user.setSessionKey(sessionKey);
user.setuName(nickName);
user.setuGender(gender);
user.setuAddress(country+" "+province+" "+city);
user.setuAvatar(avatarUrl);
user.setIsSys("0");
user.setActivityNum("3");
user.setuExtensionQr("");
user.setuExtensionId(scene);
user.wDate());
user = userService.save( user );
}else {
System.out.println("⽤户已存在");
user.("U_ID").toString());
user.("IS_SYS").toString());
}
JSONObject userInfo = getUserInfo( encrypteData, sessionKey, iv );
userInfo.put("uId", uId());
userInfo.put("isSys", IsSys());
System.out.println("根据解密算法获取的userInfo="+userInfo);
return Result.success(userInfo);
}
public static JSONObject getSessionKeyOrOpenId(String code){
//端登录code
String wxCode = code;
String requestUrl = "api.weixin.qq/sns/jscode2session?appid="+Constant.APP_ID+"&secret="+Constant.APP_SECRET+"&js_code="+wxCode+"&gr //发送post请求读取调⽤接⼝获取openid⽤户唯⼀标识
JSONObject jsonObject = JSON.parseObject( HttpSenderUtil.sendPost( requestUrl,null ));
return jsonObject;
}
public static JSONObject getUserInfo(String encryptedData,String sessionKey,String iv){
// 被加密的数据
byte[] dataByte = Base64.decode(encryptedData);
// 加密秘钥
byte[] keyByte = Base64.decode(sessionKey);
// 偏移量
byte[] ivByte = Base64.decode(iv);
try {
/
/ 如果密钥不⾜16位,那么就补⾜. 这个if 中的内容很重要
int base = 16;
if (keyByte.length % base != 0) {
int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
byte[] temp = new byte[groups * base];
Arrays.fill(temp, (byte) 0);
System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
keyByte = temp;
}
// 初始化
Security.addProvider(new BouncyCastleProvider());
Cipher cipher = Instance("AES/CBC/PKCS7Padding","BC");
SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
AlgorithmParameters parameters = Instance("AES");
parameters.init(new IvParameterSpec(ivByte));
cipher.init( Cipher.DECRYPT_MODE, spec, parameters);// 初始化
cipher.init( Cipher.DECRYPT_MODE, spec, parameters);// 初始化 byte[] resultByte = cipher.doFinal(dataByte);
if (null != resultByte && resultByte.length > 0) {
String result = new String(resultByte, "UTF-8");
return JSON.parseObject(result);
}
} catch (NoSuchAlgorithmException e) {
System.out.Message());
} catch (NoSuchPaddingException e) {
System.out.Message());
} catch (InvalidParameterSpecException e) {
System.out.Message());
} catch (IllegalBlockSizeException e) {
System.out.Message());
} catch (BadPaddingException e) {
System.out.Message());
} catch (UnsupportedEncodingException e) {
System.out.Message());
} catch (InvalidKeyException e) {
System.out.Message());
} catch (InvalidAlgorithmParameterException e) {
System.out.Message());
} catch (NoSuchProviderException e) {
System.out.Message());
}
return null;
}
}
四、使⽤
将app.js中的代码复制进app.js,然后调⽤⽅法登录即可!
注意修改其中的链接以及appid和appsecret
补充:
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.56</version>
</dependency>
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论