Home WeChat Applet Mini Program Development Example sharing of decrypting user data in the background of WeChat applet

Example sharing of decrypting user data in the background of WeChat applet

May 15, 2018 am 11:03 AM
Applets data user

This article mainly introduces the relevant information on the detailed examples of decrypting user data in the background of WeChat Mini Program. Friends in need can refer to

Detailed Examples of Decrypting User Data in the Background of WeChat Mini Program

openId: The user’s unique identifier in the current applet

Because https://api.weixin.qq.com/sns/jscode2session was recently called according to the API, the following services need to be configured. However, the official does not approve of this approach,
and recently the server configuration method has been closed. In other words, information such as user openid and region can only be obtained in the background.

This is the official process

Then the question is, how to implement the code, the following is the implementation using java background

WeChat The client code implementation is like this

wx.login({ 
   success: function (r) { 
    if (r.code) { 
     var code = r.code;//登录凭证 
     if (code) { 
      //2、调用获取用户信息接口 
      wx.getUserInfo({ 
       success: function (res) { 
        //发起网络请求 
        wx.request({ 
         url: that.data.net + '/decodeUser.json', 
         header: { 
          "content-type": "application/x-www-form-urlencoded" 
         }, 
         method: "POST", 
         data: { 
          encryptedData: res.encryptedData, 
          iv: res.iv, 
          code: code 
         }, 
         success: function (result) { 
          // wx.setStorage({ 
          //  key: 'openid', 
          //  data: res.data.openid, 
          // }) 
          console.log(result) 
         } 
        }) 
       }, 
       fail: function () { 
        console.log('获取用户信息失败') 
       } 
      }) 
     } else { 
      console.log('获取用户登录态失败!' + r.errMsg) 
     } 

    } else { 
    } 
   } 
  })
Copy after login

(server-side java) The own server sends the code to the WeChat server to obtain openid (user unique identification) and session_key (session key),
Finally, encryptedData, iv , session_key obtains user sensitive data through AES decryption

1. Obtain the secret key and process the decrypted controller

/** 
   * 解密用户敏感数据 
   * 
   * @param encryptedData 明文,加密数据 
   * @param iv      加密算法的初始向量 
   * @param code     用户允许登录后,回调内容会带上 code(有效期五分钟),开发者需要将 code 发送到开发者服务器后台,使用code 换取 session_key api,将 code 换成 openid 和 session_key 
   * @return 
   */ 
  @ResponseBody 
  @RequestMapping(value = "/decodeUser", method = RequestMethod.POST) 
  public Map decodeUser(String encryptedData, String iv, String code) { 

    Map map = new HashMap(); 

    //登录凭证不能为空 
    if (code == null || code.length() == 0) { 
      map.put("status", 0); 
      map.put("msg", "code 不能为空"); 
      return map; 
    } 

    //小程序唯一标识  (在微信小程序管理后台获取) 
    String wxspAppid = "wxd8980e77d335c871"; 
    //小程序的 app secret (在微信小程序管理后台获取) 
    String wxspSecret = "85d29ab4fa8c797423f2d7da5dd514cf"; 
    //授权(必填) 
    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对象) 
    JSONObject json = JSONObject.fromObject(sr); 
    //获取会话密钥(session_key) 
    String session_key = json.get("session_key").toString(); 
    //用户的唯一标识(openid) 
    String openid = (String) json.get("openid"); 

    //////////////// 2、对encryptedData加密数据进行AES解密 //////////////// 
    try { 
      String result = AesCbcUtil.decrypt(encryptedData, session_key, iv, "UTF-8"); 
      if (null != result && result.length() > 0) { 
        map.put("status", 1); 
        map.put("msg", "解密成功"); 

        JSONObject userInfoJSON = JSONObject.fromObject(result); 
        Map userInfo = new HashMap(); 
        userInfo.put("openId", userInfoJSON.get("openId")); 
        userInfo.put("nickName", userInfoJSON.get("nickName")); 
        userInfo.put("gender", userInfoJSON.get("gender")); 
        userInfo.put("city", userInfoJSON.get("city")); 
        userInfo.put("province", userInfoJSON.get("province")); 
        userInfo.put("country", userInfoJSON.get("country")); 
        userInfo.put("avatarUrl", userInfoJSON.get("avatarUrl")); 
        userInfo.put("unionId", userInfoJSON.get("unionId")); 
        map.put("userInfo", userInfo); 
        return map; 
      } 
    } catch (Exception e) { 
      e.printStackTrace(); 
    } 
    map.put("status", 0); 
    map.put("msg", "解密失败"); 
    return map; 
  }
Copy after login

Decryption tool class AesCbcUtil

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; 
  } 

}
Copy after login

The tool class for sending requests HttpRequest

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; 

/** 
 * Created by lsh on 2017/6/22. 
 */ 
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; 
  } 
}
Copy after login

In addition, due to the need to use the decryption tool class, this dependency must be added to the pom file

<dependency> 
  <groupId>org.bouncycastle</groupId> 
  <artifactId>bcprov-ext-jdk16</artifactId> 
  <version>1.46</version> 
  <type>jar</type> 
  <scope>compile</scope> 
</dependency>
Copy after login

In this way, bcprov can be introduced This jar package. After some reference online, I personally feel that adding this dependency is the easiest way to solve the problem.

The above is the detailed content of Example sharing of decrypting user data in the background of WeChat applet. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use Xiaohongshu account to find users? Can I find my mobile phone number? How to use Xiaohongshu account to find users? Can I find my mobile phone number? Mar 22, 2024 am 08:40 AM

With the rapid development of social media, Xiaohongshu has become one of the most popular social platforms. Users can create a Xiaohongshu account to show their personal identity and communicate and interact with other users. If you need to find a user’s Xiaohongshu number, you can follow these simple steps. 1. How to use Xiaohongshu account to find users? 1. Open the Xiaohongshu APP, click the &quot;Discover&quot; button in the lower right corner, and then select the &quot;Notes&quot; option. 2. In the note list, find the note posted by the user you want to find. Click to enter the note details page. 3. On the note details page, click the &quot;Follow&quot; button below the user's avatar to enter the user's personal homepage. 4. In the upper right corner of the user's personal homepage, click the three-dot button and select &quot;Personal Information&quot;

Use ddrescue to recover data on Linux Use ddrescue to recover data on Linux Mar 20, 2024 pm 01:37 PM

DDREASE is a tool for recovering data from file or block devices such as hard drives, SSDs, RAM disks, CDs, DVDs and USB storage devices. It copies data from one block device to another, leaving corrupted data blocks behind and moving only good data blocks. ddreasue is a powerful recovery tool that is fully automated as it does not require any interference during recovery operations. Additionally, thanks to the ddasue map file, it can be stopped and resumed at any time. Other key features of DDREASE are as follows: It does not overwrite recovered data but fills the gaps in case of iterative recovery. However, it can be truncated if the tool is instructed to do so explicitly. Recover data from multiple files or blocks to a single

Log in to Ubuntu as superuser Log in to Ubuntu as superuser Mar 20, 2024 am 10:55 AM

In Ubuntu systems, the root user is usually disabled. To activate the root user, you can use the passwd command to set a password and then use the su- command to log in as root. The root user is a user with unrestricted system administrative rights. He has permissions to access and modify files, user management, software installation and removal, and system configuration changes. There are obvious differences between the root user and ordinary users. The root user has the highest authority and broader control rights in the system. The root user can execute important system commands and edit system files, which ordinary users cannot do. In this guide, I'll explore the Ubuntu root user, how to log in as root, and how it differs from a normal user. Notice

Open source! Beyond ZoeDepth! DepthFM: Fast and accurate monocular depth estimation! Open source! Beyond ZoeDepth! DepthFM: Fast and accurate monocular depth estimation! Apr 03, 2024 pm 12:04 PM

0.What does this article do? We propose DepthFM: a versatile and fast state-of-the-art generative monocular depth estimation model. In addition to traditional depth estimation tasks, DepthFM also demonstrates state-of-the-art capabilities in downstream tasks such as depth inpainting. DepthFM is efficient and can synthesize depth maps within a few inference steps. Let’s read about this work together ~ 1. Paper information title: DepthFM: FastMonocularDepthEstimationwithFlowMatching Author: MingGui, JohannesS.Fischer, UlrichPrestel, PingchuanMa, Dmytr

Google is ecstatic: JAX performance surpasses Pytorch and TensorFlow! It may become the fastest choice for GPU inference training Google is ecstatic: JAX performance surpasses Pytorch and TensorFlow! It may become the fastest choice for GPU inference training Apr 01, 2024 pm 07:46 PM

The performance of JAX, promoted by Google, has surpassed that of Pytorch and TensorFlow in recent benchmark tests, ranking first in 7 indicators. And the test was not done on the TPU with the best JAX performance. Although among developers, Pytorch is still more popular than Tensorflow. But in the future, perhaps more large models will be trained and run based on the JAX platform. Models Recently, the Keras team benchmarked three backends (TensorFlow, JAX, PyTorch) with the native PyTorch implementation and Keras2 with TensorFlow. First, they select a set of mainstream

Slow Cellular Data Internet Speeds on iPhone: Fixes Slow Cellular Data Internet Speeds on iPhone: Fixes May 03, 2024 pm 09:01 PM

Facing lag, slow mobile data connection on iPhone? Typically, the strength of cellular internet on your phone depends on several factors such as region, cellular network type, roaming type, etc. There are some things you can do to get a faster, more reliable cellular Internet connection. Fix 1 – Force Restart iPhone Sometimes, force restarting your device just resets a lot of things, including the cellular connection. Step 1 – Just press the volume up key once and release. Next, press the Volume Down key and release it again. Step 2 – The next part of the process is to hold the button on the right side. Let the iPhone finish restarting. Enable cellular data and check network speed. Check again Fix 2 – Change data mode While 5G offers better network speeds, it works better when the signal is weaker

The vitality of super intelligence awakens! But with the arrival of self-updating AI, mothers no longer have to worry about data bottlenecks The vitality of super intelligence awakens! But with the arrival of self-updating AI, mothers no longer have to worry about data bottlenecks Apr 29, 2024 pm 06:55 PM

I cry to death. The world is madly building big models. The data on the Internet is not enough. It is not enough at all. The training model looks like "The Hunger Games", and AI researchers around the world are worrying about how to feed these data voracious eaters. This problem is particularly prominent in multi-modal tasks. At a time when nothing could be done, a start-up team from the Department of Renmin University of China used its own new model to become the first in China to make "model-generated data feed itself" a reality. Moreover, it is a two-pronged approach on the understanding side and the generation side. Both sides can generate high-quality, multi-modal new data and provide data feedback to the model itself. What is a model? Awaker 1.0, a large multi-modal model that just appeared on the Zhongguancun Forum. Who is the team? Sophon engine. Founded by Gao Yizhao, a doctoral student at Renmin University’s Hillhouse School of Artificial Intelligence.

Tesla robots work in factories, Musk: The degree of freedom of hands will reach 22 this year! Tesla robots work in factories, Musk: The degree of freedom of hands will reach 22 this year! May 06, 2024 pm 04:13 PM

The latest video of Tesla's robot Optimus is released, and it can already work in the factory. At normal speed, it sorts batteries (Tesla's 4680 batteries) like this: The official also released what it looks like at 20x speed - on a small "workstation", picking and picking and picking: This time it is released One of the highlights of the video is that Optimus completes this work in the factory, completely autonomously, without human intervention throughout the process. And from the perspective of Optimus, it can also pick up and place the crooked battery, focusing on automatic error correction: Regarding Optimus's hand, NVIDIA scientist Jim Fan gave a high evaluation: Optimus's hand is the world's five-fingered robot. One of the most dexterous. Its hands are not only tactile

See all articles