微信小程序登录处理

master
shijie 4 years ago
parent 76b053e21f
commit caf6396194
  1. 4
      dq-financial-hrms-auth/src/main/java/com/daqing/financial/hrauth/controller/UserLoginController.java
  2. 2
      dq-financial-hrms-auth/src/main/java/com/daqing/financial/hrauth/dao/UserLoginDao.java
  3. 4
      dq-financial-hrms-auth/src/main/java/com/daqing/financial/hrauth/filter/MyAuthenticationFilter.java
  4. 3
      dq-financial-hrms-auth/src/main/java/com/daqing/financial/hrauth/model/XccLoginReq.java
  5. 2
      dq-financial-hrms-auth/src/main/java/com/daqing/financial/hrauth/service/UserLoginService.java
  6. 251
      dq-financial-hrms-auth/src/main/java/com/daqing/financial/hrauth/service/impl/UserLoginServiceImpl.java
  7. 14
      dq-financial-hrms-auth/src/main/java/com/daqing/financial/hrauth/service/impl/UserServiceImpl.java
  8. 146
      dq-financial-hrms-auth/src/main/java/com/daqing/financial/hrauth/util/AES.java
  9. 342
      dq-financial-hrms-auth/src/main/java/com/daqing/financial/hrauth/util/AesCbcUtil.java
  10. 198
      dq-financial-hrms-auth/src/main/java/com/daqing/financial/hrauth/util/TestUtil.java
  11. 65
      dq-financial-hrms-auth/src/main/java/com/daqing/financial/hrauth/util/WXBizDataCrypt.java
  12. 4
      dq-financial-hrms-auth/src/main/resources/mapper/hrauth/UserLoginMapper.xml
  13. 1
      dq-financial-hrms-auth/src/test/java/com/daqing/financial/hrauth/DqFinancialHrmsAuthApplicationTests.java
  14. 2
      dq-framework-model/src/main/java/com/daqing/framework/domain/hrms/request/BindOpenIdRequest.java
  15. 2
      dq-framework-model/src/main/java/com/daqing/framework/domain/hrms/request/LoginRequest.java

@ -228,7 +228,7 @@ public class UserLoginController implements UserLoginControllerApi {
String encryptedData = xccLoginReq.getEncryptedData(); String encryptedData = xccLoginReq.getEncryptedData();
String code = xccLoginReq.getCode(); String code = xccLoginReq.getCode();
String iv = xccLoginReq.getIv(); String iv = xccLoginReq.getIv();
Map openid = userLoginService.wxAuthLogin(encryptedData,iv,code); Integer identify = xccLoginReq.getIdentify();
return ResponseResult.SUCCESS(openid); return userLoginService.wxAuthLogin(encryptedData,iv,code,identify);
} }
} }

@ -16,7 +16,7 @@ import java.util.Date;
public interface UserLoginDao extends BaseMapper<UserEntity> { public interface UserLoginDao extends BaseMapper<UserEntity> {
UserEntity getUser(String code); UserEntity getUser(String code);
int selectCount(String phoneAccount); int selectPhoneCount(String phoneAccount);
int updatePasswordByPhoneAccount(@Param("phoneAccount") String phoneAccount, @Param("password") String password); int updatePasswordByPhoneAccount(@Param("phoneAccount") String phoneAccount, @Param("password") String password);
UserEntity login(LoginRequest loginRequest); UserEntity login(LoginRequest loginRequest);

@ -100,9 +100,9 @@ public class MyAuthenticationFilter extends OncePerRequestFilter {
// 全局注入角色权限信息和登录用户基本信息 // 全局注入角色权限信息和登录用户基本信息
SecurityContextHolder.getContext().setAuthentication(authentication); SecurityContextHolder.getContext().setAuthentication(authentication);
} }
else { /* else {
throw new AccessDeniedException("TOKEN不存在,请重新登录!"); throw new AccessDeniedException("TOKEN不存在,请重新登录!");
} }*/
filterChain.doFilter(wrappedRequest, wrappedResponse); filterChain.doFilter(wrappedRequest, wrappedResponse);
} finally { } finally {
stopWatch.stop(); stopWatch.stop();

@ -8,7 +8,7 @@ import java.io.Serializable;
/** /**
* <p> * <p>
* 访问记录表 * 小程序授权登录
* </p> * </p>
* *
* @author Qyq * @author Qyq
@ -21,5 +21,6 @@ public class XccLoginReq implements Serializable {
private String iv;//加密算法的初始向量 private String iv;//加密算法的初始向量
private String code;//用户允许登录后,回调内容会带上 code(有效期五分钟),开发者需要将 code 发送到开发者服务器后台 private String code;//用户允许登录后,回调内容会带上 code(有效期五分钟),开发者需要将 code 发送到开发者服务器后台
// ,使用code 换取 session_key api,将 code 换成 openid 和 session_key // ,使用code 换取 session_key api,将 code 换成 openid 和 session_key
private Integer identify;//标识 0->员工;1->客户
} }

@ -25,5 +25,5 @@ public interface UserLoginService extends IService<UserEntity> {
int isPhoneExist(String mobile); int isPhoneExist(String mobile);
Map wxAuthLogin(String encryptedData, String iv, String code); ResponseResult wxAuthLogin(String encryptedData, String iv, String code, Integer identify);
} }

@ -85,7 +85,7 @@ public class UserLoginServiceImpl extends ServiceImpl<UserLoginDao, UserEntity>
@Override @Override
public UserLoginRequest verifyMobile(UserLoginRequest user){ public UserLoginRequest verifyMobile(UserLoginRequest user){
//校验手机账号是否存在 //校验手机账号是否存在
int count = userLoginDao.selectCount(user.getPhoneAccount()); int count = userLoginDao.selectPhoneCount(user.getPhoneAccount());
if (count == 0) { if (count == 0) {
ExceptionCast.cast(HrmsCode.PHNOE_ACCOUNT_NOT_EXIST); ExceptionCast.cast(HrmsCode.PHNOE_ACCOUNT_NOT_EXIST);
} }
@ -123,7 +123,6 @@ public class UserLoginServiceImpl extends ServiceImpl<UserLoginDao, UserEntity>
@Transactional @Transactional
public ResponseResult login(LoginRequest loginRequest) { public ResponseResult login(LoginRequest loginRequest) {
System.out.println("wechatId222================"+loginRequest.getWechatId());
//判断用户登录方式 //判断用户登录方式
UserEntity userEntity = baseMapper.login(loginRequest); UserEntity userEntity = baseMapper.login(loginRequest);
String name = null; String name = null;
@ -242,6 +241,15 @@ public class UserLoginServiceImpl extends ServiceImpl<UserLoginDao, UserEntity>
//返回用户信息 //返回用户信息
LoginResponse loginResponse = new LoginResponse(); LoginResponse loginResponse = new LoginResponse();
if(name == null || name == ""){//名称如果为空,则代表是客户的名称,小程序端登录,名称默认为微信名称
name = userEntity.getAccount();
}
if(headImg != null || headImg != ""){//头像如果为空,则默认为微信头像
if(userEntity.getHeadPortaritUrl() != null){
headImg = userEntity.getHeadPortaritUrl();
}
}
loginResponse.setAccount(name); loginResponse.setAccount(name);
loginResponse.setToken(token); loginResponse.setToken(token);
if(headImg != null) if(headImg != null)
@ -295,7 +303,7 @@ public class UserLoginServiceImpl extends ServiceImpl<UserLoginDao, UserEntity>
ExceptionCast.cast(HrmsCode.VERIFY_CODE_ILLEGAL); ExceptionCast.cast(HrmsCode.VERIFY_CODE_ILLEGAL);
} }
//根据手机账号查询是否存在该用户 //根据手机账号查询是否存在该用户
int count = userLoginDao.selectCount(bindOpenIdRequest.getPhoneAccount()); int count = userLoginDao.selectPhoneCount(bindOpenIdRequest.getPhoneAccount());
if(count > 0){ if(count > 0){
//存在,直接绑定openId //存在,直接绑定openId
userLoginDao.updateOpenIdByPhoneAccount(bindOpenIdRequest.getPhoneAccount(),bindOpenIdRequest.getWechatId()); userLoginDao.updateOpenIdByPhoneAccount(bindOpenIdRequest.getPhoneAccount(),bindOpenIdRequest.getWechatId());
@ -308,11 +316,11 @@ public class UserLoginServiceImpl extends ServiceImpl<UserLoginDao, UserEntity>
@Override @Override
public int isPhoneExist(String mobile) { public int isPhoneExist(String mobile) {
return userLoginDao.selectCount(mobile); return userLoginDao.selectPhoneCount(mobile);
} }
@Override @Override
public Map wxAuthLogin(String encryptedData, String iv,String code) { public ResponseResult wxAuthLogin(String encryptedData, String iv,String code,Integer identify) {
System.out.println("code****"+code+"encryptedData**************"+encryptedData+"iv**********"+iv); System.out.println("code****"+code+"encryptedData**************"+encryptedData+"iv**********"+iv);
System.out.println("来了小程序登录------------------------------------"); System.out.println("来了小程序登录------------------------------------");
//微信那边的接口,grant_type=authorization_code是固定的 //微信那边的接口,grant_type=authorization_code是固定的
@ -328,7 +336,6 @@ public class UserLoginServiceImpl extends ServiceImpl<UserLoginDao, UserEntity>
System.out.println("sr==================="+sr); System.out.println("sr==================="+sr);
// 解析相应内容(转换成json对象) // 解析相应内容(转换成json对象)
//JSONObject json = JSON.parseObject(url);
cn.hutool.json.JSONObject json = new cn.hutool.json.JSONObject(sr); cn.hutool.json.JSONObject json = new cn.hutool.json.JSONObject(sr);
// 获取会话密钥(session_key) // 获取会话密钥(session_key)
String session_key = json.get("session_key").toString(); String session_key = json.get("session_key").toString();
@ -339,28 +346,18 @@ public class UserLoginServiceImpl extends ServiceImpl<UserLoginDao, UserEntity>
Map map = new HashMap(); Map map = new HashMap();
//======================此处为死数据============================
encryptedData="V6E2hVgfhatfPt/octP4c6881lJ1GCsYqtzY9MzqlWTpthAw5uWJLpRoXtmO5oM7XSHS6xKqh8YVzhKmrfzbb66574fbfE7n5ADSJYlsJwem1ifm3sypW9Ys3GSBwHaQ/x+Sn3rfs+HKMJgegGn+b3R5X7eXFhrA6lFnd+/xpYB4VWztFMsIyVT85Mlv5G3vp1FryctiGjWTFDDh1kAFXQ31Cso91SuAW2muSUaHh32pJ+WBrpZ7wrEZyyuqMqA0UpZve+gonUpZjnRWXewTTWm6jvc7lMQqFA1PD13pOGKYNKD/WxtaMXPWmvN+5WVwScH7ueEeppA1/aFwsMGnDBUU/+B04WxuQxo+M4b15vIq5GxI5Qvulv1taRdA5oiI10K+9UJAm+dz/2c2ZqEIiu+QTj9gvgbJsrIWMe0Wu5qmNTj/V97furJlcVaVvJvUy0N8zrqb7unAptjL0bQUvIB0ZXVgNbGEZLmAbpQhNgpIJ0ft6LiqvIzkrRYR+sIVr+mJrCoYxhyxB8cqsHJT2w==";
session_key="Piqc8iFe6pN0i5ofq4Y6PA==";
iv="Y37DfoP3+4ysUBo8YOnfiQ==";
System.out.println("session_key======"+session_key+"openid===="+openid);
System.out.println("code****"+code+"encryptedData**************"+encryptedData+"iv**********"+iv);
//对encryptedData加密数据进行AES解密 //对encryptedData加密数据进行AES解密
try { try {
String result = WXBizDataCrypt.getInstance().decrypt(encryptedData, session_key, iv, "utf-8"); String result = WXBizDataCrypt.getInstance().decrypt(encryptedData, session_key, iv, "utf-8");
System.out.println("AES解密值==="+result); System.out.println("AES解密值==="+result);
//String result = AesCbcUtil.decrypt2(session_key,encryptedData, iv);
//String result = AesCbcUtil.decrypt(encryptedData, session_key, iv, "UTF-8");
if (null != result && result.length() > 0) { if (null != result && result.length() > 0) {
map.put("status", 1); map.put("status", 1);
map.put("msg", "解密成功"); map.put("msg", "解密成功");
JSONObject userInfoJSON = JSONObject.parseObject(result); JSONObject userInfoJSON = JSONObject.parseObject(result);
//JSONObject userInfoJSON = JSON.parseObject(result);
//cn.hutool.json.JSONObject userInfoJSON = new cn.hutool.json.JSONObject(result);
System.out.println("userInfoJSON===="+userInfoJSON); System.out.println("userInfoJSON===="+userInfoJSON);
Map userInfo = new HashMap(); Map userInfo = new HashMap();
// 解密unionId & openId;
userInfo.put("openId", userInfoJSON.get("openId")); userInfo.put("openId", userInfoJSON.get("openId"));
userInfo.put("nickName", userInfoJSON.get("nickName")); userInfo.put("nickName", userInfoJSON.get("nickName"));
userInfo.put("gender", userInfoJSON.get("gender")); userInfo.put("gender", userInfoJSON.get("gender"));
@ -368,11 +365,9 @@ public class UserLoginServiceImpl extends ServiceImpl<UserLoginDao, UserEntity>
userInfo.put("province", userInfoJSON.get("province")); userInfo.put("province", userInfoJSON.get("province"));
userInfo.put("country", userInfoJSON.get("country")); userInfo.put("country", userInfoJSON.get("country"));
userInfo.put("avatarUrl", userInfoJSON.get("avatarUrl")); userInfo.put("avatarUrl", userInfoJSON.get("avatarUrl"));
// 解密unionId & openId; userInfo.put("unionId", userInfoJSON.get("unionId"));
System.out.println("userInfoJSON==============="+userInfoJSON);
System.out.println("unionId============"+userInfoJSON.get("unionId")); System.out.println("unionId============"+userInfoJSON.get("unionId"));
userInfo.put("unionId", userInfoJSON.get("unionId"));
map.put("userInfo", userInfo); map.put("userInfo", userInfo);
} else { } else {
map.put("status", 0); map.put("status", 0);
@ -382,203 +377,37 @@ public class UserLoginServiceImpl extends ServiceImpl<UserLoginDao, UserEntity>
e.printStackTrace(); e.printStackTrace();
} }
System.out.println("map===================="+map.get("userInfo")); Map userMap = (Map<String,Object>)map.get("userInfo");
return map; String unionId = userMap.get("unionId").toString();
} String md5UnionId = Md5Util.md5(unionId);
/* @Override System.out.println("字符串格式userMap里面的unionId===="+userMap.get("unionId").toString());
public String wxAuthLogin(String encryptedData, String iv,String code) { //根据unionId查询用户是否注册过,如果已经是老用户,则直接调登录接口,如果为新用户,则先保存用户信息,再调登录
System.out.println(code); int count = userLoginDao.selectCount(new QueryWrapper<UserEntity>().eq("wechat_id",md5UnionId));
System.out.println("来了小程序登录------------------------------------");
//微信那边的接口,grant_type=authorization_code是固定的
String url = String.format(weChatConfig.getWX_AUTH_URL(),weChatConfig.getXcxAppid(),weChatConfig.getXcxAppsecret(),code);
System.out.println("url==============="+url); //根据标识判断是员工还是客户登录,如果为员工登录,则直接登录,无需保存记录,如果为客户登录,则先查询是否已注册
//发送请求给微信后端 LoginRequest loginRequest = new LoginRequest();
CloseableHttpClient httpClient= HttpClients.createDefault(); loginRequest.setWechatId(md5UnionId);
HttpGet httpGet=new HttpGet(url); loginRequest.setType(2);
InputStream inputStream=null; loginRequest.setTenDayEffective(2);
CloseableHttpResponse httpResponse=null; if(identify==0){//员工小程序登录
StringBuilder result=new StringBuilder(); if(count<=0){
try { return ResponseResult.FAIL(60001,"您不是员工,请使用客户小程序登录!");
httpResponse=httpClient.execute(httpGet);
HttpEntity entity=httpResponse.getEntity();
inputStream=entity.getContent();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
String line="";
while ((line=bufferedReader.readLine())!=null){
System.out.println(line); //这里需要使用fastjson来提取一下内容
JSONObject jsonObject= JSON.parseObject(line);
Login login=new Login();
System.out.println("jsonObject====================="+jsonObject);
System.out.println("unionId==================="+jsonObject.getString("unionid"));
login.setOpenid(jsonObject.getString("openid"));
login.setSession_key(jsonObject.getString("session_key"));
login.setUnionid(jsonObject.getString("unionid"));
result.append(login.getUnionid());
System.out.println(result.toString());
}
} catch (IOException e) {
e.printStackTrace();
} }
}else{//客户小程序登录
return result.toString(); if(count <=0){//新用户
}*/ UserEntity userEntity = new UserEntity();
userEntity.setAccount(userMap.get("nickName").toString());//账号默认为微信名称
/* @Override userEntity.setWechatId(md5UnionId);//加密后unionId
public String wxAuthLogin(String encryptedData, String iv,String code) { userEntity.setHeadPortaritUrl(userMap.get("avatarUrl").toString());//头像路径
System.out.println(code); userEntity.setCreateTime(new Date());//创建时间
System.out.println("来了小程序登录------------------------------------"); userLoginDao.insert(userEntity);
//微信那边的接口,grant_type=authorization_code是固定的
String url = String.format(weChatConfig.getWX_AUTH_URL(),weChatConfig.getXcxAppid(),weChatConfig.getXcxAppsecret(),code);
System.out.println("url==============="+url);
Map<String ,Object> baseMap = HttpUtils.doGet(url);
if(baseMap == null || baseMap.isEmpty()){ return null; }
String accessToken = (String)baseMap.get("access_token");
String openId = (String) baseMap.get("openid");
String unionId = (String) baseMap.get("unionid");
System.out.println("小程序登录openId============="+openId+"unionId=============="+unionId+"baseMap============"+baseMap);
return unionId;
}*/
/*
*//**
* 1 先按照loginInfo信息查询有无有unionID
* 2 如果有,直接返回 ,程序结束
* 3 如果没有,将用于解密的session_key获取
* 4 根据userInfo拿取encryptedData等加密数据
* 5 对加密数据进行逆解密
* 6 拿到unionID 返回,程序结
*
* userInfo TODO 注意一下通过user.getInfo获取的和通过button授权获取的格式不一样
*
*//*
@Override
public ResponseResult getUnionID(Long platformId, String userInfo, String loginInfo, HttpServletRequest request) {
Map<String, String> resLogign = null;
JSONObject resUserInfo = null;
System.out.println("--------------->>>>>进入WeChatServiceImpl");
resLogign = getUnionIDByLoginInfo(loginInfo, request);
// 加密session_key 解密需要
String session_key = resLogign.get("session_key");
if (StringUtils.isNotBlank(resLogign.get("unionid"))) {
System.out.println("返回数据,获取unionid,程序结束<<<------unionid={}"+resLogign.get("unionid"));
return ResponseResult.SUCCESS("获取unionid成功,返回数据!"+resLogign);
} else {
System.out.println("没有获取到unionid,userinfo进行对称解密操作start----->");
resUserInfo = decipherByUserInfo(session_key, userInfo, request);
if (resUserInfo != null && StringUtils.isNotEmpty(resUserInfo.toJSONString())) {
System.out.println("解密后的信息为resUserInfo:{}"+resUserInfo.toJSONString());
// 解密信息由 data.get("unionid") 获取
return ResponseResult.SUCCESS("获取解密信息成功"+resUserInfo);
}
}
return null;
}
*//**
*
* @param session_key
* @param userInfo
* @param request
* @return
*//*
private JSONObject decipherByUserInfo(String session_key, String userInfo, HttpServletRequest request) {
System.out.println("--------------->>>>>进入 decipherByUserInfo");
Map<String, String> resUserInfo = new HashMap<>();
if (!userInfo.contains("login:ok")&&!userInfo.contains("getUserInfo:ok")) {
return null;
}
JSONObject jsonUserInfo = JSONObject.parseObject(userInfo);
System.out.println("将userInfo转换成JSON,userInfo:{}"+jsonUserInfo.toJSONString());
String encryptedData = "";
String iv = "";
if (jsonUserInfo.get("detail") != null && StringUtils.isNotBlank(jsonUserInfo.get("detail").toString())) {
String detail = jsonUserInfo.get("detail").toString();
JSONObject parseObject = JSONObject.parseObject(detail);
encryptedData = (String) parseObject.get("encryptedData");
iv = (String) parseObject.get("iv");
} else {
encryptedData = (String) jsonUserInfo.get("encryptedData");
iv = (String) jsonUserInfo.get("iv");
}
System.out.println("获取解密数据解密start------------>>>解密需要的数据为:encryptedData:{},iv:{},session_key:{}"+"encryptedData===="+encryptedData+"iv===="+iv+"session_key===="+session_key);
// 被加密的数据
byte[] dataByte = Base64.decodeBase64(encryptedData);
// 加密秘钥
byte[] aeskey = Base64.decodeBase64(session_key);
// 偏移量
byte[] ivByte = Base64.decodeBase64(iv);
System.out.println("对加密数据进行Base64编码完毕------------>>>dataByte:{},aeskey:{},ivByte:{}"+dataByte.toString()+aeskey.toString()+ivByte.toString());
String newuserInfo = "";
try {
AES aes = new AES();
byte[] resultByte = aes.decrypt(dataByte, aeskey, ivByte);
if (null != resultByte && resultByte.length > 0) {
newuserInfo = new String(resultByte, "UTF-8");
System.out.println("解密完毕,解密结果为newuserInfo:{}"+newuserInfo);
return JSONObject.parseObject(newuserInfo);
} }
} catch (Exception e) {
System.out.println("解密异常!检查解密数据 {}"+newuserInfo+e);
e.printStackTrace();
} }
return null;
}
*//**
* 根据logininfo 的code尝试获取unionID
*
* @param loginInfo
* @param request
* @return
*//*
private Map<String, String> getUnionIDByLoginInfo(String loginInfo, HttpServletRequest request) {
JSONObject loginRes = null;
Map<String, Object> loginReq = new HashMap<>();
Map<String, String> loginResMap = new HashMap<>();
System.out.println("--------------->>>>>进入 getUnionIDByLoginInfo");
JSONObject loginMap = JSONObject.parseObject(loginInfo);
System.out.println("转换JSON完毕");
System.out.println("组装请求数据----start:");
String resCode = (String) loginMap.get("code");
loginReq.put("js_code", resCode);
loginReq.put("appid", weChatConfig.getXcxAppid()); // 这几个变量是自己去获取的 我做成了配置文件中
loginReq.put("secret", weChatConfig.getXcxAppsecret()); // 去这个网址看参数说明: https://developers.weixin.qq.com/miniprogram/dev/api/api-login.html#wxloginobject
loginReq.put("grant_type", "authorization_code");
System.out.println("组装请求参数完毕loginReq={}"+loginReq);
try {
System.out.println("开始发送请求到微信...url={}"+weChatConfig.getWX_AUTH_URL());
loginRes = HttpClientUtils.doGet(SysConstants.WEICHAT_UNIONID_URL, loginReq); ResponseResult result = login(loginRequest);
} catch (Exception e) { return result;
System.out.println("调用httpClient异常!异常信息={}"+e); }
throw new RuntimeException(e);
}
String openid = (String) loginRes.get("openid");
String session_key = (String) loginRes.get("session_key");
String unionid = (String) loginRes.get("unionid");
loginResMap.put("openid", openid);
loginResMap.put("unionid", unionid);
loginResMap.put("session_key", session_key);
System.out.println("https返回数据loginRes={}"+loginRes.toJSONString());
// 微信建议不要在传输中有session_key,我们在这里做一个缓存数据key=session_key_safe,value="真实的session_key+真实的openid"
// TODO
// 时间问题,这里暂不处理
// loginResMap.put("session_key", "session_key_safe");
return loginResMap;
}*/
} }

@ -62,16 +62,17 @@ public class UserServiceImpl extends ServiceImpl<UserLoginDao, UserEntity> imple
System.out.println("微信扫码加密前openId============="+openId+"unionId=============="+unionId+"baseMap============"+baseMap); System.out.println("微信扫码加密前openId============="+openId+"unionId=============="+unionId+"baseMap============"+baseMap);
//对code(回调过来的openid)加密 //对code(回调过来的openid)加密
String md5OpenId = Md5Util.md5(openId); String md5OpenId = Md5Util.md5(openId);
String md5UnionId = Md5Util.md5(unionId);
log.info("accessToken========> "+accessToken+"openId========> "+openId+"code=======> "+code+"md5OpenId============>"+md5OpenId); log.info("accessToken========> "+accessToken+"openId========> "+openId+"code=======> "+code+"md5OpenId============>"+md5OpenId);
UserEntity dbUser = userMapper.findByOpenid(md5OpenId); UserEntity dbUser = userMapper.findByOpenid(md5UnionId);
if(dbUser!=null && dbUser.getPhoneAccount()!=null) { //dbUser不为空,存在直接让它登录 if(dbUser!=null && dbUser.getPhoneAccount()!=null) { //dbUser不为空,存在直接让它登录
log.info("来了微信扫码登录~~~~~~~~~~~~~~~~~~~~~~~~~~~"); log.info("来了微信扫码登录~~~~~~~~~~~~~~~~~~~~~~~~~~~");
LoginRequest loginRequest = new LoginRequest(); LoginRequest loginRequest = new LoginRequest();
loginRequest.setTenDayEffective(1); loginRequest.setTenDayEffective(1);
loginRequest.setType(2); loginRequest.setType(2);
loginRequest.setWechatId(md5OpenId); loginRequest.setWechatId(md5UnionId);
ResponseResult login = userLoginService.login(loginRequest); ResponseResult login = userLoginService.login(loginRequest);
LoginResponse data = (LoginResponse) login.getData(); LoginResponse data = (LoginResponse) login.getData();
@ -91,8 +92,8 @@ public class UserServiceImpl extends ServiceImpl<UserLoginDao, UserEntity> imple
if(dbUser == null){//openId不存在,返回绑定手机号页面,须另写绑定手机号接口 if(dbUser == null){//openId不存在,返回绑定手机号页面,须另写绑定手机号接口
log.info("dbUser为空,openId不存在,请先绑定手机号哦~~~"); log.info("dbUser为空,openId不存在,请先绑定手机号哦~~~");
try { try {
response.sendRedirect("https://www.huorantech.cn/index/#/bind-phone?matched="+md5OpenId);//跳转绑定手机号页面 response.sendRedirect("https://www.huorantech.cn/index/#/bind-phone?matched="+md5UnionId);//跳转绑定手机号页面
//response.sendRedirect("http://8.129.127.185/dq/index.html#/bind-phone?matched="+md5OpenId);//跳转绑定手机号页面 //response.sendRedirect("http://8.129.127.185/dq/index.html#/bind-phone?matched="+md5UnionId);//跳转绑定手机号页面
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -149,7 +150,8 @@ public class UserServiceImpl extends ServiceImpl<UserLoginDao, UserEntity> imple
String unionId = (String) baseMap.get("unionid"); String unionId = (String) baseMap.get("unionid");
log.info("openId========="+openId+"unionId===="+unionId); log.info("openId========="+openId+"unionId===="+unionId);
String md5OpenId = Md5Util.md5(openId); String md5OpenId = Md5Util.md5(openId);
Integer countWeChatId = this.getBaseMapper().countWeChatId(md5OpenId); String md5UnionId = Md5Util.md5(unionId);
Integer countWeChatId = this.getBaseMapper().countWeChatId(md5UnionId);
String token = this.getBaseMapper().getTokenByUserId(Long.parseLong(state)); String token = this.getBaseMapper().getTokenByUserId(Long.parseLong(state));
if (countWeChatId > 0){ if (countWeChatId > 0){
try { try {
@ -160,7 +162,7 @@ public class UserServiceImpl extends ServiceImpl<UserLoginDao, UserEntity> imple
e.printStackTrace(); e.printStackTrace();
} }
}else { }else {
Boolean result = this.getBaseMapper().updateWeChat(Long.parseLong(state), md5OpenId); Boolean result = this.getBaseMapper().updateWeChat(Long.parseLong(state), md5UnionId);
log.info("绑定成功---------------------------------------"); log.info("绑定成功---------------------------------------");
if (result){ if (result){
try { try {

@ -1,73 +1,73 @@
package com.daqing.financial.hrauth.util; //package com.daqing.financial.hrauth.util;
//
import java.security.AlgorithmParameters; //import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException; //import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException; //import java.security.InvalidKeyException;
import java.security.Key; //import java.security.Key;
import java.security.NoSuchAlgorithmException; //import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException; //import java.security.NoSuchProviderException;
import java.security.Security; //import java.security.Security;
//
import javax.crypto.BadPaddingException; //import javax.crypto.BadPaddingException;
import javax.crypto.Cipher; //import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException; //import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException; //import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec; //import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; //import javax.crypto.spec.SecretKeySpec;
//
import org.bouncycastle.jce.provider.BouncyCastleProvider; //import org.bouncycastle.jce.provider.BouncyCastleProvider;
//
public class AES { //public class AES {
public static boolean initialized = false; // public static boolean initialized = false;
//
/** // /**
* AES对称解密工具类 // * AES对称解密工具类
* // *
* @param content // * @param content
* 密文 // * 密文
* @return // * @return
* @throws InvalidAlgorithmParameterException // * @throws InvalidAlgorithmParameterException
* @throws NoSuchProviderException // * @throws NoSuchProviderException
*/ // */
public byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte) throws InvalidAlgorithmParameterException { // public byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte) throws InvalidAlgorithmParameterException {
initialize(); // initialize();
try { // try {
// java是没有 // // java是没有
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); // Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
Key sKeySpec = new SecretKeySpec(keyByte, "AES"); // Key sKeySpec = new SecretKeySpec(keyByte, "AES");
//
cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(ivByte));// 初始化 // cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(ivByte));// 初始化
byte[] result = cipher.doFinal(content); // byte[] result = cipher.doFinal(content);
return result; // return result;
} catch (NoSuchAlgorithmException e) { // } catch (NoSuchAlgorithmException e) {
e.printStackTrace(); // e.printStackTrace();
} catch (NoSuchPaddingException e) { // } catch (NoSuchPaddingException e) {
e.printStackTrace(); // e.printStackTrace();
} catch (InvalidKeyException e) { // } catch (InvalidKeyException e) {
e.printStackTrace(); // e.printStackTrace();
} catch (IllegalBlockSizeException e) { // } catch (IllegalBlockSizeException e) {
e.printStackTrace(); // e.printStackTrace();
} catch (BadPaddingException e) { // } catch (BadPaddingException e) {
e.printStackTrace(); // e.printStackTrace();
} catch (NoSuchProviderException e) { // } catch (NoSuchProviderException e) {
e.printStackTrace(); // e.printStackTrace();
} catch (Exception e) { // } catch (Exception e) {
e.printStackTrace(); // e.printStackTrace();
} // }
return null; // return null;
} // }
//
public static void initialize() { // public static void initialize() {
if (initialized) // if (initialized)
return; // return;
Security.addProvider(new BouncyCastleProvider()); // Security.addProvider(new BouncyCastleProvider());
initialized = true; // initialized = true;
} // }
//
// 生成iv // // 生成iv
public static AlgorithmParameters generateIV(byte[] iv) throws Exception { // public static AlgorithmParameters generateIV(byte[] iv) throws Exception {
AlgorithmParameters params = AlgorithmParameters.getInstance("AES"); // AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
params.init(new IvParameterSpec(iv)); // params.init(new IvParameterSpec(iv));
return params; // return params;
} // }
} //}

@ -1,171 +1,171 @@
package com.daqing.financial.hrauth.util; //package com.daqing.financial.hrauth.util;
//
import org.apache.commons.codec.binary.Base64; //import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider; //import org.bouncycastle.jce.provider.BouncyCastleProvider;
//
import javax.crypto.*; //import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec; //import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; //import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException; //import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets; //import java.nio.charset.StandardCharsets;
import java.security.*; //import java.security.*;
import java.security.spec.InvalidParameterSpecException; //import java.security.spec.InvalidParameterSpecException;
import java.util.Arrays; //import java.util.Arrays;
//
/** ///**
* Created by yfs on 2018/3/25. // * Created by yfs on 2018/3/25.
* <p> // * <p>
* AES-128-CBC 加密方式 // * AES-128-CBC 加密方式
* // * 注:
* AES-128-CBC可以自己定义密钥偏移量 // * AES-128-CBC可以自己定义“密钥”和“偏移量“。
* AES-128是jdk自动生成的密钥 // * AES-128是jdk自动生成的“密钥”。
*/ // */
public class AesCbcUtil { //public class AesCbcUtil {
//
//
static { // static {
//BouncyCastle是一个开源的加解密解决方案,主页在http://www.bouncycastle.org/ // //BouncyCastle是一个开源的加解密解决方案,主页在http://www.bouncycastle.org/
Security.addProvider(new BouncyCastleProvider()); // Security.addProvider(new BouncyCastleProvider());
} // }
//
/** // /**
* AES解密 // * AES解密
* // *
* @param data //密文,被加密的数据 // * @param data //密文,被加密的数据
* @param key //秘钥 // * @param key //秘钥
* @param iv //偏移量 // * @param iv //偏移量
* @param encodingFormat //解密后的结果需要进行的编码 // * @param encodingFormat //解密后的结果需要进行的编码
* @return // * @return
* @throws Exception // * @throws Exception
*/ // */
public static String decrypt(String data, String key, String iv, String encodingFormat) throws Exception { // public static String decrypt(String data, String key, String iv, String encodingFormat) throws Exception {
// initialize(); //// initialize();
//
//被加密的数据 // //被加密的数据
byte[] dataByte = Base64.decodeBase64(data); // byte[] dataByte = Base64.decodeBase64(data);
//加密秘钥 // //加密秘钥
byte[] keyByte = Base64.decodeBase64(key); // byte[] keyByte = Base64.decodeBase64(key);
//偏移量 // //偏移量
byte[] ivByte = Base64.decodeBase64(iv); // byte[] ivByte = Base64.decodeBase64(iv);
//
//
try { // try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); // Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
//
SecretKeySpec spec = new SecretKeySpec(keyByte, "AES"); // SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
//
AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES"); // AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
parameters.init(new IvParameterSpec(ivByte)); // parameters.init(new IvParameterSpec(ivByte));
//
cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化 // cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
//
byte[] resultByte = cipher.doFinal(dataByte); // byte[] resultByte = cipher.doFinal(dataByte);
if (null != resultByte && resultByte.length > 0) { // if (null != resultByte && resultByte.length > 0) {
String result = new String(resultByte, encodingFormat); // String result = new String(resultByte, encodingFormat);
return result; // return result;
} // }
return null; // return null;
} catch (NoSuchAlgorithmException e) { // } catch (NoSuchAlgorithmException e) {
e.printStackTrace(); // e.printStackTrace();
} catch (NoSuchPaddingException e) { // } catch (NoSuchPaddingException e) {
e.printStackTrace(); // e.printStackTrace();
} catch (InvalidParameterSpecException e) { // } catch (InvalidParameterSpecException e) {
e.printStackTrace(); // e.printStackTrace();
} catch (InvalidKeyException e) { // } catch (InvalidKeyException e) {
e.printStackTrace(); // e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) { // } catch (InvalidAlgorithmParameterException e) {
e.printStackTrace(); // e.printStackTrace();
} catch (IllegalBlockSizeException e) { // } catch (IllegalBlockSizeException e) {
e.printStackTrace(); // e.printStackTrace();
} catch (BadPaddingException e) { // } catch (BadPaddingException e) {
e.printStackTrace(); // e.printStackTrace();
} catch (UnsupportedEncodingException e) { // } catch (UnsupportedEncodingException e) {
e.printStackTrace(); // e.printStackTrace();
} // }
//
return null; // return null;
} // }
//
/** // /**
* AES解密 // * AES解密
* // *
* @param encryptedData 消息密文 // * @param encryptedData 消息密文
* @param ivStr iv字符串 // * @param ivStr iv字符串
*/ // */
public static byte[] decrypt2(String sessionKey, String encryptedData, String ivStr) { // public static byte[] decrypt2(String sessionKey, String encryptedData, String ivStr) {
try { // try {
AlgorithmParameters params = AlgorithmParameters.getInstance("AES"); // AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
params.init(new IvParameterSpec(Base64.decodeBase64(ivStr))); // params.init(new IvParameterSpec(Base64.decodeBase64(ivStr)));
//
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); // Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(Base64.decodeBase64(sessionKey), "AES"), params); // cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(Base64.decodeBase64(sessionKey), "AES"), params);
//
String encodingFormat = "UTF-8"; // String encodingFormat = "UTF-8";
byte[] resultByte = cipher.doFinal(Base64.decodeBase64(encryptedData)); // byte[] resultByte = cipher.doFinal(Base64.decodeBase64(encryptedData));
return resultByte; // return resultByte;
/* System.out.println("resultByte===="+resultByte); ///* System.out.println("resultByte===="+resultByte);
if (null != resultByte && resultByte.length > 0) { // if (null != resultByte && resultByte.length > 0) {
String result = new String(resultByte, encodingFormat); // String result = new String(resultByte, encodingFormat);
return result; // return result;
} // }
return null;*/ // return null;*/
//return new String(PKCS7Encoder.decode(cipher.doFinal(Base64.decodeBase64(encryptedData))), StandardCharsets.UTF_8); // //return new String(PKCS7Encoder.decode(cipher.doFinal(Base64.decodeBase64(encryptedData))), StandardCharsets.UTF_8);
} catch (Exception e) { // } catch (Exception e) {
throw new RuntimeException("AES解密失败", e); // throw new RuntimeException("AES解密失败", e);
} // }
} // }
//
//
public static String decryptNew(String encryptedData, String sessionKey, String iv) throws Exception { // public static String decryptNew(String encryptedData, String sessionKey, String iv) throws Exception {
String result = ""; // String result = "";
// 被加密的数据 // // 被加密的数据
byte[] dataByte = Base64.decodeBase64(encryptedData); // byte[] dataByte = Base64.decodeBase64(encryptedData);
// 加密秘钥 // // 加密秘钥
byte[] keyByte = Base64.decodeBase64(sessionKey); // byte[] keyByte = Base64.decodeBase64(sessionKey);
// 偏移量 // // 偏移量
byte[] ivByte = Base64.decodeBase64(iv); // byte[] ivByte = Base64.decodeBase64(iv);
try { // try {
// 如果密钥不足16位,那么就补足. 这个if 中的内容很重要 // // 如果密钥不足16位,那么就补足. 这个if 中的内容很重要
int base = 16; // int base = 16;
if (keyByte.length % base != 0) { // if (keyByte.length % base != 0) {
int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0); // int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
byte[] temp = new byte[groups * base]; // byte[] temp = new byte[groups * base];
Arrays.fill(temp, (byte) 0); // Arrays.fill(temp, (byte) 0);
System.arraycopy(keyByte, 0, temp, 0, keyByte.length); // System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
keyByte = temp; // keyByte = temp;
} // }
// 初始化 // // 初始化
Security.addProvider(new BouncyCastleProvider()); // Security.addProvider(new BouncyCastleProvider());
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC"); // Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
SecretKeySpec spec = new SecretKeySpec(keyByte, "AES"); // SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES"); // AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
parameters.init(new IvParameterSpec(ivByte)); // parameters.init(new IvParameterSpec(ivByte));
// 初始化 // // 初始化
cipher.init(Cipher.DECRYPT_MODE, spec, parameters); // cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
byte[] resultByte = cipher.doFinal(dataByte); // byte[] resultByte = cipher.doFinal(dataByte);
if (null != resultByte && resultByte.length > 0) { // if (null != resultByte && resultByte.length > 0) {
result = new String(resultByte, "UTF-8"); // result = new String(resultByte, "UTF-8");
} // }
} catch (NoSuchAlgorithmException e) { // } catch (NoSuchAlgorithmException e) {
e.printStackTrace(); // e.printStackTrace();
} catch (NoSuchPaddingException e) { // } catch (NoSuchPaddingException e) {
e.printStackTrace(); // e.printStackTrace();
} catch (InvalidParameterSpecException e) { // } catch (InvalidParameterSpecException e) {
e.printStackTrace(); // e.printStackTrace();
} catch (IllegalBlockSizeException e) { // } catch (IllegalBlockSizeException e) {
e.printStackTrace(); // e.printStackTrace();
} catch (BadPaddingException e) { // } catch (BadPaddingException e) {
e.printStackTrace(); // e.printStackTrace();
} catch (UnsupportedEncodingException e) { // } catch (UnsupportedEncodingException e) {
e.printStackTrace(); // e.printStackTrace();
} catch (InvalidKeyException e) { // } catch (InvalidKeyException e) {
e.printStackTrace(); // e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) { // } catch (InvalidAlgorithmParameterException e) {
e.printStackTrace(); // e.printStackTrace();
} catch (NoSuchProviderException e) { // } catch (NoSuchProviderException e) {
e.printStackTrace(); // e.printStackTrace();
} // }
return result; // return result;
} // }
//
} //}

@ -1,198 +0,0 @@
package com.daqing.financial.hrauth.util;
import com.google.common.primitives.Bytes;
import org.apache.commons.codec.binary.Base64;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class TestUtil {
/**
* 加密
*
* @param content
* 需要加密的内容
* @param password
* 加密密码
* @return
*/
public static byte[] encrypt(String content, String password) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(password.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(byteContent);
return result; // 加密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
/**
* 解密
*
* @param content
* 待解密内容
* @param password
* 解密密钥
* @return
*/
public static byte[] decrypt(byte[] content, String password) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(password.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
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();
}
return null;
}
/**
* 将二进制转换成16进制
*
* @param buf
* @return
*/
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
* 将16进制转换为二进制
*
* @param hexStr
* @return
*/
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
/**
* 加密
*
* @param content
* 需要加密的内容
* @param password
* 加密密码
* @return
*/
public static byte[] encrypt2(String content, String password) {
try {
SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(byteContent);
return result; // 加密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws UnsupportedEncodingException, InvalidAlgorithmParameterException {
String encryptedData="+WQuaG5Tr9EU6f+Cx7OR7O8/HbVAUK77P9/BRqhdA4qYKLcw0sbS1R5DfoU+D4HEpoUCXtmRH/gP" +
"eJqYFJpauBysbadiYrZ6wYWjp5wP+HgxWnfCOk7jwR8WUdvFFDuQMhAVudnFhhNP3g4iHfCeiU5yfmN4iw" +
"gpL4txJpuZDHhyjqBqGGxntyxgxHFonbFi94e+IaPrFqigvqJXI9RGW9eXUVhZEQGeadv+eW72ucPq90KGH" +
"wPj0uUMWRWPJC8ZWp+uRUbrENiKfo9QJqiMljq/wcbz4c/u/Wd7PF4o4s02uutMjsrpYdnpw20E7DDpUIBU" +
"fIkeDmIFOIEQYPAGbTFtbHwPyyrx/r+fSihmO6PRwAlUrfhCOZ3KNkmtqZPDjqfHGrW+MeiquW5vryXL8FWy++z" +
"OVdGzymGvW6E/hSVDoTNL4+zeuxhJAXCnuPjLtYeL0EkGam8ks0KDqhZy3gUwRwrM0HFzQ1IryTMsqeLCcLMm" +
"0vWG4PEuPv5j5+V66MTGYvyyM2v67zK7Z2cn2A==";
String iv="zI+P8RVxEwMFBXcJDCemHg==";
String session_key="Piqc8iFe6pN0i5ofq4Y6PA==";
String content = encryptedData;
String password = "";
// 加密
System.out.println("加密前:" + content);
byte[] encode = encrypt(content, password);
//传输过程,不转成16进制的字符串,就等着程序崩溃掉吧
String code = parseByte2HexStr(encode);
System.out.println("密文字符串:" + code);
byte[] decode = parseHexStr2Byte(code);
// 解密
byte[] decryptResult = decrypt(decode, password);
System.out.println("decryptResult==="+decryptResult);
System.out.println("解密后:" + new String(decryptResult, "UTF-8")); //不转码会乱码
System.out.println("=========================================================");
byte[] dataByte = Base64.decodeBase64(session_key);
//byte[] d = TestUtil.parseHexStr2Byte(encryptedData);
byte[] dr = decrypt(dataByte, "");
//String re = new String(dr, "UTF-8");
//System.out.println("result====="+re);
}
}

@ -3,9 +3,16 @@ import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; import javax.crypto.spec.SecretKeySpec;
import cn.hutool.core.codec.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import sun.misc.BASE64Decoder; import sun.misc.BASE64Decoder;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;
import java.util.Map;
/** /**
* 对微信小程序用户加密数据的解密示例代码. * 对微信小程序用户加密数据的解密示例代码.
* *
@ -63,14 +70,68 @@ public class WXBizDataCrypt {
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] original = cipher.doFinal(_encryptedData); byte[] original = cipher.doFinal(_encryptedData);
byte[] bytes = PKCS7Encoder.decode(original); byte[] bytes = PKCS7Encoder.decode(original);
String originalString = new String(bytes, "ISO-8859-1"); String originalString = new String(bytes, "UTF-8");//ISO-8859-1
return originalString; return originalString;
} catch (Exception ex) { } catch (Exception ex) {
return null; return null;
} }
} }
/**
* 解密encryptedData获取用户信息
*
* @param encryptedData
* @param sessionKey
* @param iv
* @return
*/
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 = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
parameters.init(new IvParameterSpec(ivByte));
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 JSONObject.parseObject(result);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
String iv="dvIIKwlnHIneQrj1ZGhhWQ==";
String sessionKey="xUkcqKQdaK0vpVUXj8ityA==";
String encryptedData="nK44nXrhAtBbmwBNgZ+du5mJbGoEr9pyPJG3upfQq6GXK3IKDHGkec6HDxGyBGe1qCs2kwLIOzm24da4o7cb6eEeNbewj18SMsWErGE3KWfy1b2BEg1ttu8oKp9Eatsmofavn/TnZeZSXVe5hDsmJSUPPRidjVp6AWCmOiQLCjY2RiNjpVx2fdgVvrzARK6IOlYyoL0soMUQXt0jnTdza5XVUbY/iTLbVc5Hrbw52+/n2tphoBc1iFXlkkKsJiHL6482LAZ43U5ev/AWoEV/lGfs4APktlppWjdIQkXFlpnb4z5TV0S5QT4D4fxigvjIi6MgTO9CYViCVS7K3/WK0JeuMS61dKJLAriajZN1LiBJhz29jG1PctEnGS56C+o59PrUKfULvRD6U0cGLpgsVuyFM6EFVgz7NIEmBC4gOVGnOSAenkc++xVvVUf164SBMIQItVXaYSv+13Dat43CyHmN+bZowJz0ghJ730gPv3f01RqCMmjrWwQuBzZi8RuXNPIBzpBhymfvnM8QF+FjXA==";
/* Map<String, Object> userInfo = getUserInfo(encryptedData, sessionKey, iv);
System.out.println(userInfo);
String nickName = (String) userInfo.get("nickName"); //昵称
String avatarUrl = (String) userInfo.get("avatarUrl"); //头像
String unionId = (String) userInfo.get("unionId"); //unionid*/
// 需要加密的字串 // 需要加密的字串
// String appid = "wx4f4bc4dec97d474b"; // String appid = "wx4f4bc4dec97d474b";
/* String sessionKey = "tiihtNczf5v6AKRyjwEUhQ=="; /* String sessionKey = "tiihtNczf5v6AKRyjwEUhQ==";
@ -96,9 +157,11 @@ public class WXBizDataCrypt {
String iv="zI+P8RVxEwMFBXcJDCemHg=="; String iv="zI+P8RVxEwMFBXcJDCemHg==";
String sessionKey="Piqc8iFe6pN0i5ofq4Y6PA==";*/ String sessionKey="Piqc8iFe6pN0i5ofq4Y6PA==";*/
/*
String iv="Y37DfoP3+4ysUBo8YOnfiQ=="; String iv="Y37DfoP3+4ysUBo8YOnfiQ==";
String sessionKey="Piqc8iFe6pN0i5ofq4Y6PA=="; String sessionKey="Piqc8iFe6pN0i5ofq4Y6PA==";
String encryptedData="V6E2hVgfhatfPt/octP4c6881lJ1GCsYqtzY9MzqlWTpthAw5uWJLpRoXtmO5oM7XSHS6xKqh8YVzhKmrfzbb66574fbfE7n5ADSJYlsJwem1ifm3sypW9Ys3GSBwHaQ/x+Sn3rfs+HKMJgegGn+b3R5X7eXFhrA6lFnd+/xpYB4VWztFMsIyVT85Mlv5G3vp1FryctiGjWTFDDh1kAFXQ31Cso91SuAW2muSUaHh32pJ+WBrpZ7wrEZyyuqMqA0UpZve+gonUpZjnRWXewTTWm6jvc7lMQqFA1PD13pOGKYNKD/WxtaMXPWmvN+5WVwScH7ueEeppA1/aFwsMGnDBUU/+B04WxuQxo+M4b15vIq5GxI5Qvulv1taRdA5oiI10K+9UJAm+dz/2c2ZqEIiu+QTj9gvgbJsrIWMe0Wu5qmNTj/V97furJlcVaVvJvUy0N8zrqb7unAptjL0bQUvIB0ZXVgNbGEZLmAbpQhNgpIJ0ft6LiqvIzkrRYR+sIVr+mJrCoYxhyxB8cqsHJT2w=="; String encryptedData="V6E2hVgfhatfPt/octP4c6881lJ1GCsYqtzY9MzqlWTpthAw5uWJLpRoXtmO5oM7XSHS6xKqh8YVzhKmrfzbb66574fbfE7n5ADSJYlsJwem1ifm3sypW9Ys3GSBwHaQ/x+Sn3rfs+HKMJgegGn+b3R5X7eXFhrA6lFnd+/xpYB4VWztFMsIyVT85Mlv5G3vp1FryctiGjWTFDDh1kAFXQ31Cso91SuAW2muSUaHh32pJ+WBrpZ7wrEZyyuqMqA0UpZve+gonUpZjnRWXewTTWm6jvc7lMQqFA1PD13pOGKYNKD/WxtaMXPWmvN+5WVwScH7ueEeppA1/aFwsMGnDBUU/+B04WxuQxo+M4b15vIq5GxI5Qvulv1taRdA5oiI10K+9UJAm+dz/2c2ZqEIiu+QTj9gvgbJsrIWMe0Wu5qmNTj/V97furJlcVaVvJvUy0N8zrqb7unAptjL0bQUvIB0ZXVgNbGEZLmAbpQhNgpIJ0ft6LiqvIzkrRYR+sIVr+mJrCoYxhyxB8cqsHJT2w==";
*/
/* String iv="sAUv8qjwP8j/Ql9KLgA4iQ=="; /* String iv="sAUv8qjwP8j/Ql9KLgA4iQ==";
String sessionKey="H5lUk3IPIIENRdLxzLi2Hg=="; String sessionKey="H5lUk3IPIIENRdLxzLi2Hg==";

@ -20,12 +20,12 @@
<select id="getUser" parameterType="string" resultType="com.daqing.framework.domain.hrms.UserEntity"> <select id="getUser" parameterType="string" resultType="com.daqing.framework.domain.hrms.UserEntity">
SELECT id,account,password FROM hrms_user WHERE account = #{account} SELECT id,account,password FROM hrms_user WHERE account = #{account}
</select> </select>
<select id="selectCount" resultType="java.lang.Integer"> <select id="selectPhoneCount" resultType="java.lang.Integer">
select count(1) from hrms_user where phone_account = #{phoneAccount} select count(1) from hrms_user where phone_account = #{phoneAccount}
</select> </select>
<select id="login" parameterType="com.daqing.framework.domain.hrms.request.LoginRequest" resultType="com.daqing.framework.domain.hrms.UserEntity"> <select id="login" parameterType="com.daqing.framework.domain.hrms.request.LoginRequest" resultType="com.daqing.framework.domain.hrms.UserEntity">
select id,account,phone_account,password,login_num from hrms_user select id,account,phone_account,password,login_num,head_portarit_url from hrms_user
where del_or_not = 0 and status = 0 where del_or_not = 0 and status = 0
<if test="phone != null and phone != '' "> <if test="phone != null and phone != '' ">
and (phone_account = #{phone} or account = #{phone}) and (phone_account = #{phone} or account = #{phone})

@ -1,6 +1,5 @@
package com.daqing.financial.hrauth; package com.daqing.financial.hrauth;
import com.daqing.financial.hrauth.util.AesCbcUtil;
import io.swagger.models.auth.In; import io.swagger.models.auth.In;
import java.io.BufferedReader; import java.io.BufferedReader;

@ -24,7 +24,7 @@ public class BindOpenIdRequest implements Serializable {
private String phoneAccount; private String phoneAccount;
/** /**
* openId * unionId
*/ */
private String wechatId; private String wechatId;

@ -14,7 +14,7 @@ public class LoginRequest {
@ApiModelProperty(value = "登录类型(1:手机号 2:微信登录)") @ApiModelProperty(value = "登录类型(1:手机号 2:微信登录)")
private int type; private int type;
@ApiModelProperty(value = "微信唯一编号") @ApiModelProperty(value = "微信唯一编号(unionId)")
private String wechatId; private String wechatId;
@ApiModelProperty(value = "密码") @ApiModelProperty(value = "密码")

Loading…
Cancel
Save