package com.llny.controller; import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.llny.utils.AesCbcUtil;
import com.llny.utils.DataResponse;
import com.llny.utils.HttpRequest;
import org.springframework.web.bind.annotation.*; import java.util.HashMap;
import java.util.Map; @RestController
@RequestMapping(value = "/wechat")
public class WeChaConnView {
/**
* 解密用户敏感数据
*
* @param encryptedData 明文,加密数据
* @param iv 加密算法的初始向量
* @param code 用户允许登录后,回调内容会带上 code(有效期五分钟),开发者需要将 code 发送到开发者服务器后台,使用code 换取 session_key api,将 code 换成 openid 和 session_key
* @return
*/
@ResponseBody
@PostMapping(value = "/decodeUser")
public DataResponse decodeUser(@RequestParam("encryptedData")String encryptedData, @RequestParam("iv")String iv, @RequestParam("code")String code) {
DataResponse response = new DataResponse();
Map<String, Object> map = new HashMap<>(); //登录凭证不能为空
if (code == null || code.length() == 0) {
/*map.put("status", 0);
map.put("msg", "code 不能为空"); return map;*/
response.setResult_code("failed");
response.setResult_msg("code 不能为空"); return response;
} //小程序唯一标识 (在微信小程序管理后台获取)
String wxspAppid = "appid";
//小程序的 app secret (在微信小程序管理后台获取)
String wxspSecret = "appsecret";
//授权(必填)
String grant_type = "authorization_code"; //////////////// 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid ////////////////
//请求参数
String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;
//发送请求
String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
//解析相应内容(转换成json对象)
Gson gson = new Gson();
JsonObject json = gson.fromJson(sr, JsonObject.class);
System.out.println(json);
// JSONObject json = JSONObject.fromObject(sr); if (json.get("session_key") == null) {
/*map.put("status", 0);
map.put("msg", "解密失败"); return map;*/
response.setResult_code("failed");
response.setResult_msg("解密失败:" + json.get("errmsg").toString().replaceAll("\"", "")); return response;
}
//获取会话密钥(session_key)
String session_key = json.get("session_key").toString();
//用户的唯一标识(openid)
// String openid = (String) json.get("openid");
String openid = json.get("openid").toString(); //////////////// 2、对encryptedData加密数据进行AES解密 ////////////////
String data = encryptedData.replaceAll("[+]", "%2B");
try {
String result = AesCbcUtil.decrypt(data, session_key, iv, "UTF-8");
if (null != result && result.length() > 0) {
/*map.put("status", 1);
map.put("msg", "解密成功"); */ JsonObject userInfoJSON = gson.fromJson(result, JsonObject.class);
// JSONObject userInfoJSON = JSONObject.fromObject(result);
System.out.println("user: " + userInfoJSON);
Map<String, Object> userInfo = new HashMap<>();
userInfo.put("openId", openid.replaceAll("\"", ""));
userInfo.put("phoneNumber", userInfoJSON.get("phoneNumber").toString().replaceAll("\"", ""));
userInfo.put("purePhoneNumber", userInfoJSON.get("purePhoneNumber").toString().replaceAll("\"", ""));
userInfo.put("countryCode", userInfoJSON.get("countryCode").toString().replaceAll("\"", ""));
map.put("userInfo", userInfo);
System.out.println("map: " + map); response.setResult_code("success");
response.setResult_msg("解密成功");
response.setData(userInfo); return response;
}
} catch (Exception e) {
e.printStackTrace();
}
/*map.put("status", 0);
map.put("msg", "解密失败"); return map;*/
response.setResult_code("failed");
response.setResult_msg("解密失败"); return response;
} }
package com.llny.utils;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider; import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidParameterSpecException; /**
* Created by lsh
* AES-128-CBC 加密方式
* 注:
* AES-128-CBC可以自己定义“密钥”和“偏移量“。
* AES-128是jdk自动生成的“密钥”。
*/
public class AesCbcUtil {
static {
//BouncyCastle是一个开源的加解密解决方案,主页在http://www.bouncycastle.org/
Security.addProvider(new BouncyCastleProvider());
}
/**
* AES解密
*
* @param data //密文,被加密的数据
* @param key //秘钥
* @param iv //偏移量
* @param encodingFormat //解密后的结果需要进行的编码
* @return
* @throws Exception
*/
public static String decrypt(String data, String key, String iv, String encodingFormat) throws Exception {
// initialize(); //被加密的数据
byte[] dataByte = Base64.decodeBase64(data);
//加密秘钥
byte[] keyByte = Base64.decodeBase64(key);
//偏移量
byte[] ivByte = Base64.decodeBase64(iv); try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); 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, encodingFormat);
return result;
}
return null;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidParameterSpecException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} return null;
}
}
package com.llny.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map; public class HttpRequest {
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
} /**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
} }
package com.llny.utils;

import com.github.pagehelper.PageInfo;

public class DataResponse {

    //信息详情
private String result_msg; //成功失败信息
private String result_code; //公共通知编码
private String result_num; private PageInfo page;
private Object data; public DataResponse(){} public DataResponse(Object data){
this.data = data;
} public DataResponse(String result_code,String result_msg){
this.result_code = result_code;
this.result_msg = result_msg;
} public DataResponse(String result_code,String result_msg,String result_num){
this.result_code = result_code;
this.result_msg = result_msg;
this.result_num = result_num;
} public String getResult_num() {
return result_num;
} public void setResult_num(String result_num) {
this.result_num = result_num;
} public String getResult_msg() {
return result_msg;
} public void setResult_msg(String result_msg) {
this.result_msg = result_msg;
} public String getResult_code() {
return result_code;
} public void setResult_code(String result_code) {
this.result_code = result_code;
} public Object getData() {
return data;
} public void setData(Object data) { this.data = data;
} public PageInfo getPage() {
return page;
} public void setPage(PageInfo page) {
this.page = page;
}
}

注意:小程序传encryptedData到服务器时,encryptedData中的加号在传输到服务器时都变成了空格,导致解码失败。解决方法是传encryptedData时,把“+”用“%2B”替换。或者在服务器替换空格为加号!!!!!!

参考一位仁兄,成功,仅作记录

java 后台解密小程序前端传过来的信息,解密手机号的更多相关文章

  1. 「小程序JAVA实战」小程序上传短视频(46)

    转自:https://idig8.com/2018/09/14/xiaochengxujavashizhanxiaochengxushangchuanduanshipin45/ 个人信息:用户上传短视 ...

  2. Java springboot支付宝小程序授权,获取用户信息,支付及回调

    参考官方文档https://opendocs.alipay.com/mini/introduce/pay 支付宝小程序的支付和微信小程序的支付一样第一步都是要获取到用户的唯一标识,在微信中我们获取到的 ...

  3. uni-app开发经验分享二十: 微信小程序 授权登录 获取详细信息 获取手机号

    授权页面 因为微信小程序提供的 权限弹窗 只能通用户确认授权 所以可以 写一个授权页面,让用户点击 来获取用户相关信息 然后再配合后台就可以完成登录 <button class="bt ...

  4. 微信小程序上传多张图片,及php后台处理

    微信小程序上传多张图片,级小程序页面布局直接来代码index.wxml <view class='body' style='width:{{windowWidth}}px;height:{{wi ...

  5. 「小程序JAVA实战」小程序的视频点赞功能开发(62)

    转自:https://idig8.com/2018/09/24/xiaochengxujavashizhanxiaochengxudeshipindianzangongnengkaifa61/ 视频点 ...

  6. 微信小程序前端与myeclipse的数据交换过程(SSH)

    这是我个人探究微信小程序前端与后端之间的数据交换的过程,再结合个人所学的SSH框架, 编程工具用myEclipse2014工具.当然,前提是后台的项目要部署到tomcat服务器上才行, 然后总结了从后 ...

  7. 小程序上传多图片多附件多视频 c#后端

    前言: 最近在研究微信小程序,本人自己是C#写后端的;感觉小程序挺好玩的,就自己研究了一下:刚好今天又给我需求,通过小程序上传多图 然后C#后端保存到服务器: 用NET明白 前端上传需要用到流,然后就 ...

  8. 打造一款 刷Java 知识的小程序(二)

    学习Java的神器已上线,面向广大Java爱好者! 之前写的一篇:打造一款 刷Java 知识的小程序(一) 一.第二版做了什么? 第一版小程序只具有初级展示功能,知识点都是hardcode在代码里面的 ...

  9. Taro 微信小程序 上传文件到minio

    小程序前端上传文件不建议直接引用minio的js npm包,一来是这个包本身较大,会影响小程序的体积,二来是ak sk需要放到前端存储,不够安全,因此建议通过请求后端拿到签名数据后上传. 由于小程序的 ...

随机推荐

  1. Linkerd 金丝雀部署与 A/B 测试

    本指南向您展示如何使用 Linkerd 和 Flagger 来自动化金丝雀部署与 A/B 测试. 前提条件 Flagger 需要 Kubernetes 集群 v1.16 或更新版本和 Linkerd ...

  2. eladmin-plus V2.0.0 发布,单表链式调用更丝滑

    一.项目简介 eladmin的mybatis-plus版本,单表使用链式调用,代码更简洁,调用更便捷.目前更新到2021年7月.项目基于 Spring Boot 2.4.2 . Mybatis-plu ...

  3. 离线安装rpm包并解决依赖(升级vsftpd为例)

    背景  实际开发中,我们的linux服务器是处理离线状态的,并不能访问互联网.如果此时要在linux上安装或者升级软件,就只能通过rpm包的安装方式.rpm包安装有一个缺陷,就是不能处理安装包的依赖问 ...

  4. S7-200通过以太网模块,使用kepware与ifix建立通讯连接要点

    在前阵子项目改造中,需要利用先前的S7-200 PLC与ifix进行通讯,故而,在做好上位机后,在现场实际测试了下.通过CP243-1以太网模块,顺利与KEPWARE建立连接,其中当然也有些要点要注意 ...

  5. 租了一台华为云耀云服务器,却直接被封公网ip,而且是官方的bug导致!

    小弟在博客园也有十多个年头了,因为离开了.net圈子,所以很少发文,今天可算是被华为云气疯了.写下这篇文章,大家也要注意自查一下,避免无端端被封公网ip. 因为小弟创业公司业务发展,需要一个公网做宣传 ...

  6. 用AutoHotkey的热字串功能启动常用电脑程序软件 Version 2 Build 20191214

    ; 用AutoHotkey的热字串功能启动常用电脑程序软件 Version 2 Build 20191214 ; 电脑上的快捷键太多了,记都记不住,容易冲突和搞混,所以做了个热字串启动; 用法:运行此 ...

  7. 自学linux——11.shell入门

    shell 基础 1.shell介绍(内置脚本) 程序开发的效率非常高,依赖于功能强大的命令可以迅速地完成开发任务(批处理) 语法简单,代码写起来比较轻松,简单易学 (1)什么是shell shell ...

  8. docker版LAMP(PHP+MYSQL+APACHE)配置

    最近在搭测试环境,一开始就在vagant和docker之间来回折腾.两者其实都非常适合用来搭开发环境:但最终让我决定用Docker的原因是因为Vagant在hyper-v下出现了一些奇怪的问题,所以D ...

  9. burp暴力破解之md5和绕过验证码

    Burpsuite是一个功能强大的工具,也是一个比较复杂的工具 本节主要说明一下burp的intruder模块中的2个技巧 1.md5加密 我们在payload Processing中的add选项可以 ...

  10. Jms - SSRF - 代码审计

    在先知上看见一人发的文章.. 一看ID这么熟悉 原来是一个群友 唉 自己审计这么垃圾 几百年没搞过了 然后玩玩吧 一打开源码 我吐了 ctrl+alt+l格式化下代码 顺眼多了 然后Seay走了一波 ...