轻源码

  • QingYuanMa.com
  • 全球最大的互联网技术和资源下载平台
搜索
一起源码网 门户 终极进阶 查看主题

微信小程序用户数据解密

发布者: jiduqishi | 发布时间: 2017-2-26 02:16| 查看数: 4428| 评论数: 1|帖子模式

本文作者:Jaer_zk,来自原文地址

参考链接:

官方文档

官方指引图

按照官方引导图一步一步操作

1、获取code

  1. onLoad: function (options) {
  2. // 页面初始化 options为页面跳转所带来的参数
  3. let that = this
  4. wx.login({
  5. success: function (res) {
  6. // success
  7. let code = res.code
  8. that.setData({ code: code })
  9. wx.getUserInfo({
  10. success: function (res) {
  11. // success
  12. that.setData({ userInfo: res.userInfo })
  13. that.setData({ iv: res.iv })
  14. that.setData({ encryptedData: res.encryptedData })
  15. that.get3rdSession()
  16. }
  17. })
  18. }
  19. })
  20. }

2、发送code到第三方服务器,获取3rd_session

  1. get3rdSession:function(){
  2. let that = this
  3. wx.request({
  4. url: 'https://localhost:8443/get3rdSession',
  5. data: {
  6. code: this.data.code
  7. },
  8. method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
  9. // header: {}, // 设置请求的 header
  10. success: function (res) {
  11. // success
  12. var sessionId = res.data.session;
  13. that.setData({ sessionId: sessionId })
  14. wx.setStorageSync('sessionId', sessionId)
  15. that.decodeUserInfo()
  16. }
  17. })
  18. }

3、在第三方服务器上发送appid、appsecret、code到微信服务器换取session_key和openid

这里使用JFinal搭建的服务器

Redis配置

  1. public void configPlugin(Plugins me) {
  2. //用于缓存userinfo模块的redis服务
  3. RedisPlugin userInfoRedis = new RedisPlugin("userInfo","localhost");
  4. me.add(userInfoRedis);
  5. }

获取第三方session

  1. public void get3rdSession() {
  2. //获取名为userInfoRedis Cache对象
  3. Cache userInfoCache = Redis.use("userInfo");
  4. String sessionId = "";
  5. JSONObject json = new JSONObject();
  6. String code = getPara("code");
  7. String url = "" + code + "&grant_type=authorization_code";
  8. //执行命令生成3rd_session
  9. String session = ExecLinuxCMDUtil.instance.exec("cat /dev/urandom |od -x | tr -d ' '| head -n 1").toString();
  10. json.put("session", session);
  11. //创建默认的httpClient实例
  12. CloseableHttpClient httpClient = getHttpClient();
  13. try {
  14. //用get方法发送http请求
  15. HttpGet get = new HttpGet(url);
  16. System.out.println("执行get请求:...." + get.getURI());
  17. CloseableHttpResponse httpResponse = null;
  18. //发送get请求
  19. httpResponse = httpClient.execute(get);
  20. try {
  21. //response实体
  22. HttpEntity entity = httpResponse.getEntity();
  23. if (null != entity) {
  24. String result = EntityUtils.toString(entity);
  25. System.out.println(result);
  26. JSONObject resultJson = JSONObject.fromObject(result);
  27. String session_key = resultJson.getString("session_key");
  28. String openid = resultJson.getString("openid");
  29. //session存储
  30. userInfoCache.set(session,session_key+","+openid);
  31. }
  32. } finally {
  33. httpResponse.close();
  34. }
  35. } catch (Exception e) {
  36. e.printStackTrace();
  37. } finally {
  38. try {
  39. closeHttpClient(httpClient);
  40. } catch (IOException e) {
  41. e.printStackTrace();
  42. }
  43. }
  44. renderJson(json);
  45. }
  46. private CloseableHttpClient getHttpClient() {
  47. return HttpClients.createDefault();
  48. }
  49. private void closeHttpClient(CloseableHttpClient client) throws IOException {
  50. if (client != null) {
  51. client.close();
  52. }
  53. }

ExecLinuxCMDUtil.Java

  1. import java.io.InputStreamReader;
  2. import java.io.LineNumberReader;
  3. /**
  4. * javalinux环境下执行linux命令,然后返回命令返回值。
  5. * Created by LJaer on 16/12/22.
  6. */
  7. public class ExecLinuxCMDUtil {
  8. public static final ExecLinuxCMDUtil instance = new ExecLinuxCMDUtil();
  9. public static Object exec(String cmd) {
  10. try {
  11. String[] cmdA = { "/bin/sh", "-c", cmd };
  12. Process process = Runtime.getRuntime().exec(cmdA);
  13. LineNumberReader br = new LineNumberReader(new InputStreamReader(
  14. process.getInputStream()));
  15. StringBuffer sb = new StringBuffer();
  16. String line;
  17. while ((line = br.readLine()) != null) {
  18. System.out.println(line);
  19. sb.append(line).append("\n");
  20. }
  21. return sb.toString();
  22. } catch (Exception e) {
  23. e.printStackTrace();
  24. }
  25. return null;
  26. }
  27. }

4、解密用户数据

  1. decodeUserInfo:function(){
  2. let that = this
  3. wx.request({
  4. url: 'https://localhost:8443/decodeUserInfo',
  5. data: {
  6. encryptedData: that.data.encryptedData,
  7. iv: that.data.iv,
  8. session: wx.getStorageSync('sessionId')
  9. },
  10. method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
  11. // header: {}, // 设置请求的 header
  12. success: function (res) {
  13. // success
  14. console.log(res)
  15. }
  16. })
  17. }

console输出结果:

后端解密代码

  1. /**
  2. * 解密用户敏感数据
  3. */
  4. public void decodeUserInfo(){
  5. String encryptedData = getPara("encryptedData");
  6. String iv = getPara("iv");
  7. String session = getPara("session");
  8. //从缓存中获取session_key
  9. //获取名称为userInfoRedis Cache对象
  10. Cache userInfoRedis = Redis.use("userInfo");
  11. Object wxSessionObj = userInfoRedis.get(session);
  12. if(null==wxSessionObj){
  13. renderNull();
  14. }
  15. String wxSessionStr = (String)wxSessionObj;
  16. String session_key = wxSessionStr.split(",")[0];
  17. try {
  18. byte[] resultByte = AESUtil.instance.decrypt(Base64.decodeBase64(encryptedData), Base64.decodeBase64(session_key), Base64.decodeBase64(iv));
  19. if(null != resultByte && resultByte.length > 0){
  20. String userInfo = new String(resultByte, "UTF-8");
  21. System.out.println(userInfo);
  22. JSONObject json = JSONObject.fromObject(userInfo); //将字符串{“id”:1}
  23. renderJson(json);
  24. }
  25. } catch (InvalidAlgorithmParameterException e) {
  26. e.printStackTrace();
  27. } catch (UnsupportedEncodingException e) {
  28. e.printStackTrace();
  29. }
  30. }

AESUtil.java

  1. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  2. import javax.crypto.BadPaddingException;
  3. import javax.crypto.Cipher;
  4. import javax.crypto.IllegalBlockSizeException;
  5. import javax.crypto.NoSuchPaddingException;
  6. import javax.crypto.spec.IvParameterSpec;
  7. import javax.crypto.spec.SecretKeySpec;
  8. import java.security.*;
  9. public class AESUtil {
  10. public static final AESUtil instance = new AESUtil();
  11. public static boolean initialized = false;
  12. /**
  13. * AES解密
  14. * @param content 密文
  15. * @return
  16. * @throws InvalidAlgorithmParameterException
  17. * @throws NoSuchProviderException
  18. */
  19. public byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte) throws InvalidAlgorithmParameterException {
  20. initialize();
  21. try {
  22. Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
  23. Key sKeySpec = new SecretKeySpec(keyByte, "AES");
  24. cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(ivByte));// 初始化
  25. byte[] result = cipher.doFinal(content);
  26. return result;
  27. } catch (NoSuchAlgorithmException e) {
  28. e.printStackTrace();
  29. } catch (NoSuchPaddingException e) {
  30. e.printStackTrace();
  31. } catch (InvalidKeyException e) {
  32. e.printStackTrace();
  33. } catch (IllegalBlockSizeException e) {
  34. e.printStackTrace();
  35. } catch (BadPaddingException e) {
  36. e.printStackTrace();
  37. } catch (NoSuchProviderException e) {
  38. // TODO Auto-generated catch block
  39. e.printStackTrace();
  40. } catch (Exception e) {
  41. // TODO Auto-generated catch block
  42. e.printStackTrace();
  43. }
  44. return null;
  45. }
  46. public static void initialize(){
  47. if (initialized) return;
  48. Security.addProvider(new BouncyCastleProvider());
  49. initialized = true;
  50. }
  51. //生成iv
  52. public static AlgorithmParameters generateIV(byte[] iv) throws Exception{
  53. AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
  54. params.init(new IvParameterSpec(iv));
  55. return params;
  56. }
  57. }

最新评论

zuojurong 发表于 2022-4-26 19:48
源代码2为什么看不了

轻源码让程序更轻更快

QingYuanMa.com

工作时间 周一至周六 8:00-17:30

侵权处理

客服QQ点击咨询

关注抖音号

定期抽VIP

Copyright © 2016-2021 https://www.171739.xyz/ 滇ICP备13200218号

快速回复 返回顶部 返回列表