首頁 微信小程式 小程式開發 關於微信小程式中用戶資料解密的介紹

關於微信小程式中用戶資料解密的介紹

Jun 26, 2018 pm 03:57 PM
微信小程式 使用者資料

這篇文章主要介紹了微信小程式用戶資料解密詳細介紹的相關資料,需要的朋友可以參考下

微信小程式用戶資料解密

#官方指引圖:

引導圖一步一步操作

1、取得code

onLoad: function (options) {
  // 页面初始化 options为页面跳转所带来的参数
  let that = this
  wx.login({
   success: function (res) {
    // success
    let code = res.code
    that.setData({ code: code })
    wx.getUserInfo({
     success: function (res) {
      // success
      that.setData({ userInfo: res.userInfo })
      that.setData({ iv: res.iv })
      that.setData({ encryptedData: res.encryptedData })
      that.get3rdSession()
     }
    })
   }
 })
}
登入後複製

2、傳送code到第三方伺服器,取得3rd_session

#
get3rdSession:function(){
  let that = this
  wx.request({
   url: 'https://localhost:8443/get3rdSession',
   data: {
    code: this.data.code
   },
   method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
   // header: {}, // 设置请求的 header
   success: function (res) {
    // success
    var sessionId = res.data.session;
    that.setData({ sessionId: sessionId })
    wx.setStorageSync('sessionId', sessionId)
    that.decodeUserInfo()
   }
  })
 }
登入後複製

3、在第三方伺服器上傳送appid、 appsecret、code到微信伺服器換取session_key和openid

這裡使用JFinal搭建的伺服器

Redis配置

public void configPlugin(Plugins me) {
  //用于缓存userinfo模块的redis服务
  RedisPlugin userInfoRedis = new RedisPlugin("userInfo","localhost");
  me.add(userInfoRedis);
}
登入後複製

#來取得第三方session

public void get3rdSession() {
  //获取名为userInfo的Redis Cache对象
  Cache userInfoCache = Redis.use("userInfo");
  String sessionId = "";
  JSONObject json = new JSONObject();
  String code = getPara("code");
  String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx7560b8008e2c445d&secret=f1af3312b7038513fd17dd9cbc3b357c&js_code=" + code + "&grant_type=authorization_code";
  //执行命令生成3rd_session
  String session = ExecLinuxCMDUtil.instance.exec("cat /dev/urandom |od -x | tr -d ' '| head -n 1").toString();
  json.put("session", session);
  //创建默认的httpClient实例
  CloseableHttpClient httpClient = getHttpClient();
  try {
    //用get方法发送http请求
    HttpGet get = new HttpGet(url);
    System.out.println("执行get请求:...." + get.getURI());
    CloseableHttpResponse httpResponse = null;
    //发送get请求
    httpResponse = httpClient.execute(get);
    try {
      //response实体
      HttpEntity entity = httpResponse.getEntity();
      if (null != entity) {
        String result = EntityUtils.toString(entity);
        System.out.println(result);
        JSONObject resultJson = JSONObject.fromObject(result);
        String session_key = resultJson.getString("session_key");
        String openid = resultJson.getString("openid");
        //session存储
        userInfoCache.set(session,session_key+","+openid);
        }
      } finally {
        httpResponse.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        closeHttpClient(httpClient);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    renderJson(json);
}
private CloseableHttpClient getHttpClient() {
  return HttpClients.createDefault();
}

private void closeHttpClient(CloseableHttpClient client) throws IOException {
  if (client != null) {
    client.close();
  }
}
登入後複製

ExecLinuxCMDUtil.Java

import java.io.InputStreamReader;
import java.io.LineNumberReader;

/**
 * java在linux环境下执行linux命令,然后返回命令返回值。
 * Created by LJaer on 16/12/22.
 */
public class ExecLinuxCMDUtil {
  public static final ExecLinuxCMDUtil instance = new ExecLinuxCMDUtil();

  public static Object exec(String cmd) {
    try {
      String[] cmdA = { "/bin/sh", "-c", cmd };
      Process process = Runtime.getRuntime().exec(cmdA);
      LineNumberReader br = new LineNumberReader(new InputStreamReader(
          process.getInputStream()));
      StringBuffer sb = new StringBuffer();
      String line;
      while ((line = br.readLine()) != null) {
        System.out.println(line);
        sb.append(line).append("\n");
      }
      return sb.toString();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
}
登入後複製

##4、解密使用者資料

decodeUserInfo:function(){
  let that = this
  wx.request({
   url: 'https://localhost:8443/decodeUserInfo',
   data: {
    encryptedData: that.data.encryptedData,
    iv: that.data.iv,
    session: wx.getStorageSync('sessionId')
   },
   method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
   // header: {}, // 设置请求的 header
   success: function (res) {
    // success
    console.log(res)
   }
  })
}
登入後複製

console輸出結果:

#後端解密程式碼



#

/**
 * 解密用户敏感数据
 */
public void decodeUserInfo(){
  String encryptedData = getPara("encryptedData");
  String iv = getPara("iv");
  String session = getPara("session");
  //从缓存中获取session_key
  //获取名称为userInfo的Redis Cache对象
  Cache userInfoRedis = Redis.use("userInfo");
  Object wxSessionObj = userInfoRedis.get(session);
  if(null==wxSessionObj){
    renderNull();
  }
  String wxSessionStr = (String)wxSessionObj;
  String session_key = wxSessionStr.split(",")[0];


  try {
    byte[] resultByte = AESUtil.instance.decrypt(Base64.decodeBase64(encryptedData), Base64.decodeBase64(session_key), Base64.decodeBase64(iv));
    if(null != resultByte && resultByte.length > 0){
      String userInfo = new String(resultByte, "UTF-8");
      System.out.println(userInfo);
      JSONObject json = JSONObject.fromObject(userInfo); //将字符串{“id”:1}
      renderJson(json);
    }
  } catch (InvalidAlgorithmParameterException e) {
    e.printStackTrace();
  } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
  }
}
登入後複製

AESUtil.java

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.security.*;

public class AESUtil {
  public static final AESUtil instance = new AESUtil();

  public static boolean initialized = false;

  /**
   * AES解密
   * @param content 密文
   * @return
   * @throws InvalidAlgorithmParameterException
   * @throws NoSuchProviderException
   */
  public byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte) throws InvalidAlgorithmParameterException {
    initialize();
    try {
      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
      Key sKeySpec = new SecretKeySpec(keyByte, "AES");

      cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(ivByte));// 初始化
      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();
    } catch (NoSuchProviderException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return null;
  }

  public static void initialize(){
    if (initialized) return;
    Security.addProvider(new BouncyCastleProvider());
    initialized = true;
  }
  //生成iv
  public static AlgorithmParameters generateIV(byte[] iv) throws Exception{
    AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
    params.init(new IvParameterSpec(iv));
    return params;
  }
}
登入後複製

以上就是本文的全部內容,希望對大家的學習有幫助,更多相關內容請關注PHP中文網! 相關推薦:

######微信小程式透過保存圖片分享到朋友圈的功能實現###############關於微信小程序收藏功能的實作###############微信小程式如何取得openid及使用者資訊##################### #####

以上是關於微信小程式中用戶資料解密的介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

閒魚微信小程式正式上線 閒魚微信小程式正式上線 Feb 10, 2024 pm 10:39 PM

閒魚官方微信小程式悄悄上線,在小程式中可以發布閒置與買家/賣家私訊交流、查看個人資料及訂單、搜尋物品等,有用好奇閒魚微信小程式叫什麼,現在快來看一下。閒魚微信小程式叫什麼答案:閒魚,閒置交易二手買賣估價回收。 1、在小程式中可以發布閒置、與買家/賣家私訊交流、查看個人資料及訂單、搜尋指定物品等功能;2、在小程式的頁面中有首頁、附近、發閒置、訊息、我的5項功能;3、想要使用的話必要要開通微信支付才可以購買;

微信小程式實現圖片上傳功能 微信小程式實現圖片上傳功能 Nov 21, 2023 am 09:08 AM

微信小程式實現圖片上傳功能隨著行動網路的發展,微信小程式已經成為了人們生活中不可或缺的一部分。微信小程式不僅提供了豐富的應用場景,還支援開發者自訂功能,其中包括圖片上傳功能。本文將介紹如何在微信小程式中實作圖片上傳功能,並提供具體的程式碼範例。一、前期準備工作在開始編寫程式碼之前,我們需要先下載並安裝微信開發者工具,並註冊成為微信開發者。同時,也需要了解微信

實作微信小程式中的下拉式選單效果 實作微信小程式中的下拉式選單效果 Nov 21, 2023 pm 03:03 PM

實現微信小程式中的下拉式選單效果,需要具體程式碼範例隨著行動互聯網的普及,微信小程式成為了網路開發的重要一環,越來越多的人開始關注和使用微信小程式。微信小程式的開發相比傳統的APP開發更加簡單快捷,但也需要掌握一定的開發技巧。在微信小程式的開發中,下拉式選單是一個常見的UI元件,實現了更好的使用者操作體驗。本文將詳細介紹如何在微信小程式中實現下拉式選單效果,並提供具

實現微信小程式中的圖片濾鏡效果 實現微信小程式中的圖片濾鏡效果 Nov 21, 2023 pm 06:22 PM

實現微信小程式中的圖片濾鏡效果隨著社群媒體應用程式的流行,人們越來越喜歡在照片中應用濾鏡效果,以增強照片的藝術效果和吸引力。在微信小程式中也可以實現圖片濾鏡效果,為使用者提供更多有趣和創意的照片編輯功能。本文將介紹如何在微信小程式中實現圖片濾鏡效果,並提供具體的程式碼範例。首先,我們需要在微信小程式中使用canvas元件來載入和編輯圖片。 canvas元件可以在頁面

閒魚微信小程式叫什麼 閒魚微信小程式叫什麼 Feb 27, 2024 pm 01:11 PM

閒魚官方微信小程式已經悄悄上線,它為用戶提供了一個便捷的平台,讓你可以輕鬆地發布和交易閒置物品。在小程式中,你可以與買家或賣家進行私訊交流,查看個人資料和訂單,以及搜尋你想要的物品。那麼閒魚在微信小程式中究竟叫什麼呢,這篇教學攻略將為您詳細介紹,想要了解的用戶們快來跟著本文繼續閱讀吧!閒魚微信小程式叫什麼答案:閒魚,閒置交易二手買賣估價回收。 1、在小程式中可以發布閒置、與買家/賣家私訊交流、查看個人資料及訂單、搜尋指定物品等功能;2、在小程式的頁面中有首頁、附近、發閒置、訊息、我的5項功能;3、

使用微信小程式實現輪播圖切換效果 使用微信小程式實現輪播圖切換效果 Nov 21, 2023 pm 05:59 PM

使用微信小程式實現輪播圖切換效果微信小程式是一種輕量級的應用程序,具有簡單、高效的開發和使用特點。在微信小程式中,實作輪播圖切換效果是常見的需求。本文將介紹如何使用微信小程式實現輪播圖切換效果,並給出具體的程式碼範例。首先,在微信小程式的頁面檔案中,新增一個輪播圖元件。例如,可以使用<swiper>標籤來實現輪播圖的切換效果。在該組件中,可以透過b

實作微信小程式中的滑動刪除功能 實作微信小程式中的滑動刪除功能 Nov 21, 2023 pm 06:22 PM

實作微信小程式中的滑動刪除功能,需要具體程式碼範例隨著微信小程式的流行,開發者在開發過程中經常會遇到一些常見功能的實作問題。其中,滑動刪除功能是常見、常用的功能需求。本文將為大家詳細介紹如何在微信小程式中實現滑動刪除功能,並給出具體的程式碼範例。一、需求分析在微信小程式中,滑動刪除功能的實作涉及以下要點:列表展示:要顯示可滑動刪除的列表,每個列表項目需要包

實現微信小程式中的圖片旋轉效果 實現微信小程式中的圖片旋轉效果 Nov 21, 2023 am 08:26 AM

實現微信小程式中的圖片旋轉效果,需要具體程式碼範例微信小程式是一種輕量級的應用程序,為用戶提供了豐富的功能和良好的用戶體驗。在小程式中,開發者可以利用各種元件和API來實現各種效果。其中,圖片旋轉效果是一種常見的動畫效果,可以為小程式增添趣味性和視覺效果。在微信小程式中實作圖片旋轉效果,需要使用小程式提供的動畫API。以下是一個具體的程式碼範例,展示如何在小程

See all articles