微信数据解密程序简单实现

开发过微信程序的,小程序的基本都知道微信小程序从微信服务那边获取到的数据好多一部分数据都是加密的,所以你在取到这些数据的时候想往我们自己的数据库进行备份数据的话就需要对这些加密的数据进行解密,解密完成才能往我们自己的数据库进行数据同步。好了直接上代码了。。。。。在此附上一份微信数据解密的流程图供大家熟悉----------------------


(服务端 java)自己的服务器发送code到微信服务器获取openid(用户唯一标识)和session_key(会话密钥),
最后将encryptedData、iv、session_key通过AES解密获取到用户敏感数据
好了上Controller层代码--》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》

1、获取秘钥并处理解密的controller

  1. /**
  2. * 解密用户敏感数据
  3. *
  4. * @param encryptedData 明文,加密数据
  5. * @param iv 加密算法的初始向量
  6. * @param code 用户允许登录后,回调内容会带上 code(有效期五分钟),开发者需要将 code 发送到开发者服务器后台,使用code 换取 session_key api,将 code 换成 openid 和 session_key
  7. * @return
  8. */
  9. @ResponseBody
  10. @RequestMapping(value = "/decodeUser", method = RequestMethod.POST)
  11. public Map decodeUser(String encryptedData, String iv, String code) {
  12. Map map = new HashMap();
  13. //登录凭证不能为空
  14. if (code == null || code.length() == 0) {
  15. map.put( "status", 0);
  16. map.put( "msg", "code 不能为空");
  17. return map;
  18. }
  19. //小程序唯一标识 (在做小程序的时候无论是公众号还是小程序都需要申请账号注册,所以在注册成功后会有一个唯一标识id
  20.               在微信小程序管理后台获取)
  21. String wxspAppid = "wxd8980e77d335c871";
  22. //小程序的 app secret (secret 同样是在注册成功后获取到的随机码,在微信小程序管理后台获取)
  23. String wxspSecret = "85d29ab4fa8c797423f2d7da5dd514cf";
  24. //授权(这个code就是前台获取到的微信数据那边的授权码,这里写死了,必填)
  25. String grant_type = "authorization_code";
  26. //////////////// 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid ////////////////
  27. //请求参数
  28. String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;
  29. //发送请求
  30. String sr = HttpRequest.sendGet( "https://api.weixin.qq.com/sns/jscode2session", params);
  31. //解析相应内容(转换成json对象)
  32. JSONObject json = JSONObject.fromObject(sr);
  33. //获取会话密钥(session_key)
  34. String session_key = json.get( "session_key").toString();
  35. //用户的唯一标识(openid)
  36. String openid = (String) json.get( "openid");
  37. //////////////// 2、对encryptedData加密数据进行AES解密 ////////////////
  38. try {
  39. String result = AesCbcUtil.decrypt(encryptedData, session_key, iv, "UTF-8");
  40. if ( null != result && result.length() > 0) {
  41. map.put( "status", 1);
  42. map.put( "msg", "解密成功");
  43.                    // 这个时候就可以去注入我们自己的service接口去往自己的数据库去同步数据了
  44. JSONObject userInfoJSON = JSONObject.fromObject(result);
  45. Map userInfo = new HashMap();
  46. userInfo.put( "openId", userInfoJSON.get( "openId"));
  47. userInfo.put( "nickName", userInfoJSON.get( "nickName"));
  48. userInfo.put( "gender", userInfoJSON.get( "gender"));
  49. userInfo.put( "city", userInfoJSON.get( "city"));
  50. userInfo.put( "province", userInfoJSON.get( "province"));
  51. userInfo.put( "country", userInfoJSON.get( "country"));
  52. userInfo.put( "avatarUrl", userInfoJSON.get( "avatarUrl"));
  53. userInfo.put( "unionId", userInfoJSON.get( "unionId"));
  54. map.put( "userInfo", userInfo);
  55. return map;
  56. }
  57. } catch (Exception e) {
  58. e.printStackTrace();
  59. }
  60. map.put( "status", 0);
  61. map.put( "msg", "解密失败");
  62. return map;
  63. }

》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》上需要解密的工具类--------------

解密工具类 AesCbcUtil 

  1. import org.apache.commons.codec.binary.Base64;
  2. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  3. import javax.crypto.BadPaddingException;
  4. import javax.crypto.Cipher;
  5. import javax.crypto.IllegalBlockSizeException;
  6. import javax.crypto.NoSuchPaddingException;
  7. import javax.crypto.spec.IvParameterSpec;
  8. import javax.crypto.spec.SecretKeySpec;
  9. import java.io.UnsupportedEncodingException;
  10. import java.security.*;
  11. import java.security.spec.InvalidParameterSpecException;
  12. /**
  13. * Created by lsh
  14. * AES-128-CBC 加密方式
  15. * 注:
  16. * AES-128-CBC可以自己定义“密钥”和“偏移量“。
  17. * AES-128是jdk自动生成的“密钥”。
  18. */
  19. public class AesCbcUtil {
  20. static {
  21. //BouncyCastle是一个开源的加解密解决方案,主页在http://www.bouncycastle.org/
  22. Security.addProvider( new BouncyCastleProvider());
  23. }
  24. /**
  25. * AES解密
  26. *
  27. * @param data //密文,被加密的数据
  28. * @param key //秘钥
  29. * @param iv //偏移量
  30. * @param encodingFormat //解密后的结果需要进行的编码
  31. * @return
  32. * @throws Exception
  33. */
  34. public static String decrypt(String data, String key, String iv, String encodingFormat) throws Exception {
  35. // initialize();
  36. //被加密的数据
  37. byte[] dataByte = Base64.decodeBase64(data);
  38. //加密秘钥
  39. byte[] keyByte = Base64.decodeBase64(key);
  40. //偏移量
  41. byte[] ivByte = Base64.decodeBase64(iv);
  42. try {
  43. Cipher cipher = Cipher.getInstance( "AES/CBC/PKCS7Padding");
  44. SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
  45. AlgorithmParameters parameters = AlgorithmParameters.getInstance( "AES");
  46. parameters.init( new IvParameterSpec(ivByte));
  47. cipher.init(Cipher.DECRYPT_MODE, spec, parameters); // 初始化
  48. byte[] resultByte = cipher.doFinal(dataByte);
  49. if ( null != resultByte && resultByte.length > 0) {
  50. String result = new String(resultByte, encodingFormat);
  51. return result;
  52. }
  53. return null;
  54. } catch (NoSuchAlgorithmException e) {
  55. e.printStackTrace();
  56. } catch (NoSuchPaddingException e) {
  57. e.printStackTrace();
  58. } catch (InvalidParameterSpecException e) {
  59. e.printStackTrace();
  60. } catch (InvalidKeyException e) {
  61. e.printStackTrace();
  62. } catch (InvalidAlgorithmParameterException e) {
  63. e.printStackTrace();
  64. } catch (IllegalBlockSizeException e) {
  65. e.printStackTrace();
  66. } catch (BadPaddingException e) {
  67. e.printStackTrace();
  68. } catch (UnsupportedEncodingException e) {
  69. e.printStackTrace();
  70. }
  71. return null;
  72. }
  73. }


》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》继续上Util工具类---

发送请求的工具类HttpRequest  



  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.io.PrintWriter;
  5. import java.net.URL;
  6. import java.net.URLConnection;
  7. import java.util.List;
  8. import java.util.Map;
  9. /**
  10. * Created by lsh on 2017/6/22.
  11. */
  12. public class HttpRequest {
  13. /**
  14. * 向指定URL发送GET方法的请求
  15. *
  16. * @param url
  17. * 发送请求的URL
  18. * @param param
  19. * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  20. * @return URL 所代表远程资源的响应结果
  21. */
  22. public static String sendGet(String url, String param) {
  23. String result = "";
  24. BufferedReader in = null;
  25. try {
  26. String urlNameString = url + "?" + param;
  27. URL realUrl = new URL(urlNameString);
  28. // 打开和URL之间的连接
  29. URLConnection connection = realUrl.openConnection();
  30. // 设置通用的请求属性
  31. connection.setRequestProperty( "accept", "*/*");
  32. connection.setRequestProperty( "connection", "Keep-Alive");
  33. connection.setRequestProperty( "user-agent",
  34. "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  35. // 建立实际的连接
  36. connection.connect();
  37. // 获取所有响应头字段
  38. Map<String, List<String>> map = connection.getHeaderFields();
  39. // 遍历所有的响应头字段
  40. for (String key : map.keySet()) {
  41. System.out.println(key + "--->" + map.get(key));
  42. }
  43. // 定义 BufferedReader输入流来读取URL的响应
  44. in = new BufferedReader( new InputStreamReader(
  45. connection.getInputStream()));
  46. String line;
  47. while ((line = in.readLine()) != null) {
  48. result += line;
  49. }
  50. } catch (Exception e) {
  51. System.out.println( "发送GET请求出现异常!" + e);
  52. e.printStackTrace();
  53. }
  54. // 使用finally块来关闭输入流
  55. finally {
  56. try {
  57. if (in != null) {
  58. in.close();
  59. }
  60. } catch (Exception e2) {
  61. e2.printStackTrace();
  62. }
  63. }
  64. return result;
  65. }
  66. /**
  67. * 向指定 URL 发送POST方法的请求
  68. *
  69. * @param url
  70. * 发送请求的 URL
  71. * @param param
  72. * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  73. * @return 所代表远程资源的响应结果
  74. */
  75. public static String sendPost(String url, String param) {
  76. PrintWriter out = null;
  77. BufferedReader in = null;
  78. String result = "";
  79. try {
  80. URL realUrl = new URL(url);
  81. // 打开和URL之间的连接
  82. URLConnection conn = realUrl.openConnection();
  83. // 设置通用的请求属性
  84. conn.setRequestProperty( "accept", "*/*");
  85. conn.setRequestProperty( "connection", "Keep-Alive");
  86. conn.setRequestProperty( "user-agent",
  87. "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  88. // 发送POST请求必须设置如下两行
  89. conn.setDoOutput( true);
  90. conn.setDoInput( true);
  91. // 获取URLConnection对象对应的输出流
  92. out = new PrintWriter(conn.getOutputStream());
  93. // 发送请求参数
  94. out.print(param);
  95. // flush输出流的缓冲
  96. out.flush();
  97. // 定义BufferedReader输入流来读取URL的响应
  98. in = new BufferedReader(
  99. new InputStreamReader(conn.getInputStream()));
  100. String line;
  101. while ((line = in.readLine()) != null) {
  102. result += line;
  103. }
  104. } catch (Exception e) {
  105. System.out.println( "发送 POST 请求出现异常!"+e);
  106. e.printStackTrace();
  107. }
  108. //使用finally块来关闭输出流、输入流
  109. finally{
  110. try{
  111. if(out!= null){
  112. out.close();
  113. }
  114. if(in!= null){
  115. in.close();
  116. }
  117. }
  118. catch(IOException ex){
  119. ex.printStackTrace();
  120. }
  121. }
  122. return result;
  123. }
  124. }


》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》请看下边的依赖=======

  1. 由于需求所以需要解密的工具类需要加上这个jar的依赖关系:
  1.            <dependency>
  2. <groupId>org.bouncycastle</groupId>
  3. <artifactId>bcprov-ext-jdk16</artifactId>
  4. <version> 1.46</version>
  5. <type>jar</type>
  6. <scope>compile</scope>
  7. </dependency>

这样才能引入bcprov这个jar包。加这个依赖是最容易解决问题的。
微信运动的小程序,解密这块也要用到。到此完毕-------------------希望能对诸位有帮助。       









  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.io.PrintWriter;
  5. import java.net.URL;
  6. import java.net.URLConnection;
  7. import java.util.List;
  8. import java.util.Map;
  9. /**
  10. * Created by lsh on 2017/6/22.
  11. */
  12. public class HttpRequest {
  13. /**
  14. * 向指定URL发送GET方法的请求
  15. *
  16. * @param url
  17. * 发送请求的URL
  18. * @param param
  19. * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  20. * @return URL 所代表远程资源的响应结果
  21. */
  22. public static String sendGet(String url, String param) {
  23. String result = "";
  24. BufferedReader in = null;
  25. try {
  26. String urlNameString = url + "?" + param;
  27. URL realUrl = new URL(urlNameString);
  28. // 打开和URL之间的连接
  29. URLConnection connection = realUrl.openConnection();
  30. // 设置通用的请求属性
  31. connection.setRequestProperty( "accept", "*/*");
  32. connection.setRequestProperty( "connection", "Keep-Alive");
  33. connection.setRequestProperty( "user-agent",
  34. "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  35. // 建立实际的连接
  36. connection.connect();
  37. // 获取所有响应头字段
  38. Map<String, List<String>> map = connection.getHeaderFields();
  39. // 遍历所有的响应头字段
  40. for (String key : map.keySet()) {
  41. System.out.println(key + "--->" + map.get(key));
  42. }
  43. // 定义 BufferedReader输入流来读取URL的响应
  44. in = new BufferedReader( new InputStreamReader(
  45. connection.getInputStream()));
  46. String line;
  47. while ((line = in.readLine()) != null) {
  48. result += line;
  49. }
  50. } catch (Exception e) {
  51. System.out.println( "发送GET请求出现异常!" + e);
  52. e.printStackTrace();
  53. }
  54. // 使用finally块来关闭输入流
  55. finally {
  56. try {
  57. if (in != null) {
  58. in.close();
  59. }
  60. } catch (Exception e2) {
  61. e2.printStackTrace();
  62. }
  63. }
  64. return result;
  65. }
  66. /**
  67. * 向指定 URL 发送POST方法的请求
  68. *
  69. * @param url
  70. * 发送请求的 URL
  71. * @param param
  72. * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  73. * @return 所代表远程资源的响应结果
  74. */
  75. public static String sendPost(String url, String param) {
  76. PrintWriter out = null;
  77. BufferedReader in = null;
  78. String result = "";
  79. try {
  80. URL realUrl = new URL(url);
  81. // 打开和URL之间的连接
  82. URLConnection conn = realUrl.openConnection();
  83. // 设置通用的请求属性
  84. conn.setRequestProperty( "accept", "*/*");
  85. conn.setRequestProperty( "connection", "Keep-Alive");
  86. conn.setRequestProperty( "user-agent",
  87. "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  88. // 发送POST请求必须设置如下两行
  89. conn.setDoOutput( true);
  90. conn.setDoInput( true);
  91. // 获取URLConnection对象对应的输出流
  92. out = new PrintWriter(conn.getOutputStream());
  93. // 发送请求参数
  94. out.print(param);
  95. // flush输出流的缓冲
  96. out.flush();
  97. // 定义BufferedReader输入流来读取URL的响应
  98. in = new BufferedReader(
  99. new InputStreamReader(conn.getInputStream()));
  100. String line;
  101. while ((line = in.readLine()) != null) {
  102. result += line;
  103. }
  104. } catch (Exception e) {
  105. System.out.println( "发送 POST 请求出现异常!"+e);
  106. e.printStackTrace();
  107. }
  108. //使用finally块来关闭输出流、输入流
  109. finally{
  110. try{
  111. if(out!= null){
  112. out.close();
  113. }
  114. if(in!= null){
  115. in.close();
  116. }
  117. }
  118. catch(IOException ex){
  119. ex.printStackTrace();
  120. }
  121. }
  122. return result;
  123. }
  124. }

猜你喜欢

转载自blog.csdn.net/Lenovozwq/article/details/80985567