有關小程序的JAVA后臺解密encryptedData獲取openid及用戶信息

先貼上工具類,可獲取openid及session_key,session_key在解密時會用到,這里還需要用到幾個jar包

**bouncycastle-jce-jdk13-112.jar**

**xfire-core-1.2.6.jar**

百度搜一下就有

如果使用maven可以采用以下方法引入

<dependency>

? <groupId>bouncycastle</groupId>

? <artifactId>bouncycastle-jce-jdk13</artifactId>

? <version>112</version>

</dependency>

<dependency>

<groupId>org.codehaus.xfire</groupId>

<artifactId>xfire-core</artifactId>

<version>1.2.6</version>

</dependency>


GetOpenid.java獲取信息工具類

```

package com.hongbao.utils;

import java.io.UnsupportedEncodingException;

import java.security.AlgorithmParameters;

import java.security.InvalidAlgorithmParameterException;

import java.security.InvalidKeyException;

import java.security.NoSuchAlgorithmException;

import java.security.NoSuchProviderException;

import java.security.Security;

import java.security.spec.InvalidParameterSpecException;

import java.util.Arrays;

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 org.bouncycastle.jce.provider.BouncyCastleProvider;

import org.codehaus.xfire.util.Base64;

import net.sf.json.JSONObject;

/**

*

* @author silen

* 獲取微信信息工具類

*/

public class GetOpenid {

String appid = "wxd81c8f4c18******";

String secret = "7bebc83146c9979ce08d22f244******";

//可獲取openid及session_key,其實這里openid不需要獲取,encryptedData解密后包含openid

public String get(String js_code) throws Exception {

//官方接口,需要自己提供appid,secret和js_code

String requestUrl = "https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code="+js_code+"&grant_type=authorization_code";

//HttpRequestor是一個網絡請求工具類,貼在了下面

String oppid = new HttpRequestor().doGet(requestUrl);

JSONObject oppidObj = JSONObject.fromObject(oppid);

String openid = (String) oppidObj.get("openid");

String session_key = (String) oppidObj.get("session_key");

return session_key;

}

/**

* 獲取信息

? ? */

? ? public JSONObject getUserInfo(String encryptedData,String sessionkey,String iv){

? ? ? ? // 被加密的數據

? ? ? ? byte[] dataByte = Base64.decode(encryptedData);

? ? ? ? // 加密秘鑰

? ? ? ? byte[] keyByte = Base64.decode(sessionkey);

? ? ? ? // 偏移量

? ? ? ? byte[] ivByte = Base64.decode(iv);

? ? ? ? try {

? ? ? ? ? ? ? // 如果密鑰不足16位,那么就補足.? 這個if 中的內容很重要

? ? ? ? ? ? int base = 16;

? ? ? ? ? ? if (keyByte.length % base != 0) {

? ? ? ? ? ? ? ? int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);

? ? ? ? ? ? ? ? byte[] temp = new byte[groups * base];

? ? ? ? ? ? ? ? Arrays.fill(temp, (byte) 0);

? ? ? ? ? ? ? ? System.arraycopy(keyByte, 0, temp, 0, keyByte.length);

? ? ? ? ? ? ? ? keyByte = temp;

? ? ? ? ? ? }

? ? ? ? ? ? // 初始化

? ? ? ? ? ? Security.addProvider(new BouncyCastleProvider());

? ? ? ? ? ? Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");

? ? ? ? ? ? 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, "UTF-8");

? ? ? ? ? ? ? ? return JSONObject.fromObject(result);

? ? ? ? ? ? }

? ? ? ? } catch (NoSuchAlgorithmException e) {

? ? ? ? ? ? e.printStackTrace();

? ? ? ? } catch (NoSuchPaddingException e) {

? ? ? ? ? ? e.printStackTrace();

? ? ? ? } catch (InvalidParameterSpecException e) {

? ? ? ? ? ? e.printStackTrace();

? ? ? ? } catch (IllegalBlockSizeException e) {

? ? ? ? ? ? e.printStackTrace();

? ? ? ? } catch (BadPaddingException e) {

? ? ? ? ? ? e.printStackTrace();

? ? ? ? } catch (UnsupportedEncodingException e) {

? ? ? ? ? ? e.printStackTrace();

? ? ? ? } catch (InvalidKeyException e) {

? ? ? ? ? ? e.printStackTrace();

? ? ? ? } catch (InvalidAlgorithmParameterException e) {

? ? ? ? ? ? e.printStackTrace();

? ? ? ? } catch (NoSuchProviderException e) {

? ? ? ? ? ? e.printStackTrace();

? ? ? ? }

? ? ? ? return null;

? ? }

}

```

網絡請求工具類,在使用官方提供的接口獲取信息的時候使用,在上面的類中已經有使用方法,很簡單

HttpRequestor.java

```

package com.hongbao.utils;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.io.OutputStreamWriter;

import java.net.HttpURLConnection;

import java.net.InetSocketAddress;

import java.net.Proxy;

import java.net.URL;

import java.net.URLConnection;

import java.util.Iterator;

import java.util.Map;

public class HttpRequestor {

? ? private String charset = "utf-8";

? ? ? ? private Integer connectTimeout = null;

? ? ? ? private Integer socketTimeout = null;

? ? ? ? private String proxyHost = null;

? ? ? ? private Integer proxyPort = null;


? ? ? ? /**

? ? ? ? * Do GET request

? ? ? ? * @param url

? ? ? ? * @return

? ? ? ? * @throws Exception

? ? ? ? * @throws IOException

? ? ? ? */

? ? ? ? public String doGet(String url) throws Exception {


? ? ? ? ? ? URL localURL = new URL(url);


? ? ? ? ? ? URLConnection connection = openConnection(localURL);

? ? ? ? ? ? HttpURLConnection httpURLConnection = (HttpURLConnection)connection;


? ? ? ? ? ? httpURLConnection.setRequestProperty("Accept-Charset", charset);

? ? ? ? ? ? httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");


? ? ? ? ? ? InputStream inputStream = null;

? ? ? ? ? ? InputStreamReader inputStreamReader = null;

? ? ? ? ? ? BufferedReader reader = null;

? ? ? ? ? ? StringBuffer resultBuffer = new StringBuffer();

? ? ? ? ? ? String tempLine = null;


? ? ? ? ? ? if (httpURLConnection.getResponseCode() >= 300) {

? ? ? ? ? ? ? ? throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());

? ? ? ? ? ? }


? ? ? ? ? ? try {

? ? ? ? ? ? ? ? inputStream = httpURLConnection.getInputStream();

? ? ? ? ? ? ? ? inputStreamReader = new InputStreamReader(inputStream,"UTF-8");

? ? ? ? ? ? ? ? reader = new BufferedReader(inputStreamReader);


? ? ? ? ? ? ? ? while ((tempLine = reader.readLine()) != null) {

? ? ? ? ? ? ? ? ? ? resultBuffer.append(tempLine);

? ? ? ? ? ? ? ? }


? ? ? ? ? ? } finally {


? ? ? ? ? ? ? ? if (reader != null) {

? ? ? ? ? ? ? ? ? ? reader.close();

? ? ? ? ? ? ? ? }


? ? ? ? ? ? ? ? if (inputStreamReader != null) {

? ? ? ? ? ? ? ? ? ? inputStreamReader.close();

? ? ? ? ? ? ? ? }


? ? ? ? ? ? ? ? if (inputStream != null) {

? ? ? ? ? ? ? ? ? ? inputStream.close();

? ? ? ? ? ? ? ? }


? ? ? ? ? ? }

? ? ? ? ? ? return resultBuffer.toString();

? ? ? ? }


? ? ? ? /**

? ? ? ? * Do POST request

? ? ? ? * @param url

? ? ? ? * @param parameterMap

? ? ? ? * @return

? ? ? ? * @throws Exception

? ? ? ? */

? ? ? ? public String doPost(String url, Map parameterMap) throws Exception {


? ? ? ? ? ? /* Translate parameter map to parameter date string */

? ? ? ? ? ? StringBuffer parameterBuffer = new StringBuffer();

? ? ? ? ? ? if (parameterMap != null) {

? ? ? ? ? ? ? ? Iterator iterator = parameterMap.keySet().iterator();

? ? ? ? ? ? ? ? String key = null;

? ? ? ? ? ? ? ? String value = null;

? ? ? ? ? ? ? ? while (iterator.hasNext()) {

? ? ? ? ? ? ? ? ? ? key = (String)iterator.next();

? ? ? ? ? ? ? ? ? ? if (parameterMap.get(key) != null) {

? ? ? ? ? ? ? ? ? ? ? ? value = (String)parameterMap.get(key);

? ? ? ? ? ? ? ? ? ? } else {

? ? ? ? ? ? ? ? ? ? ? ? value = "";

? ? ? ? ? ? ? ? ? ? }


? ? ? ? ? ? ? ? ? ? parameterBuffer.append(key).append("=").append(value);

? ? ? ? ? ? ? ? ? ? if (iterator.hasNext()) {

? ? ? ? ? ? ? ? ? ? ? ? parameterBuffer.append("&");

? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }


? ? ? ? ? ? System.out.println("POST parameter : " + parameterBuffer.toString());


? ? ? ? ? ? URL localURL = new URL(url);


? ? ? ? ? ? URLConnection connection = openConnection(localURL);

? ? ? ? ? ? HttpURLConnection httpURLConnection = (HttpURLConnection)connection;


? ? ? ? ? ? httpURLConnection.setDoOutput(true);

? ? ? ? ? ? httpURLConnection.setRequestMethod("POST");

? ? ? ? ? ? httpURLConnection.setRequestProperty("Accept-Charset", charset);

? ? ? ? ? ? httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

? ? ? ? ? ? httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterBuffer.length()));


? ? ? ? ? ? OutputStream outputStream = null;

? ? ? ? ? ? OutputStreamWriter outputStreamWriter = null;

? ? ? ? ? ? InputStream inputStream = null;

? ? ? ? ? ? InputStreamReader inputStreamReader = null;

? ? ? ? ? ? BufferedReader reader = null;

? ? ? ? ? ? StringBuffer resultBuffer = new StringBuffer();

? ? ? ? ? ? String tempLine = null;


? ? ? ? ? ? try {

? ? ? ? ? ? ? ? outputStream = httpURLConnection.getOutputStream();

? ? ? ? ? ? ? ? outputStreamWriter = new OutputStreamWriter(outputStream);


? ? ? ? ? ? ? ? outputStreamWriter.write(parameterBuffer.toString());

? ? ? ? ? ? ? ? outputStreamWriter.flush();


? ? ? ? ? ? ? ? if (httpURLConnection.getResponseCode() >= 300) {

? ? ? ? ? ? ? ? ? ? throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());

? ? ? ? ? ? ? ? }


? ? ? ? ? ? ? ? inputStream = httpURLConnection.getInputStream();

? ? ? ? ? ? ? ? inputStreamReader = new InputStreamReader(inputStream);

? ? ? ? ? ? ? ? reader = new BufferedReader(inputStreamReader);


? ? ? ? ? ? ? ? while ((tempLine = reader.readLine()) != null) {

? ? ? ? ? ? ? ? ? ? resultBuffer.append(tempLine);

? ? ? ? ? ? ? ? }


? ? ? ? ? ? } finally {


? ? ? ? ? ? ? ? if (outputStreamWriter != null) {

? ? ? ? ? ? ? ? ? ? outputStreamWriter.close();

? ? ? ? ? ? ? ? }


? ? ? ? ? ? ? ? if (outputStream != null) {

? ? ? ? ? ? ? ? ? ? outputStream.close();

? ? ? ? ? ? ? ? }


? ? ? ? ? ? ? ? if (reader != null) {

? ? ? ? ? ? ? ? ? ? reader.close();

? ? ? ? ? ? ? ? }


? ? ? ? ? ? ? ? if (inputStreamReader != null) {

? ? ? ? ? ? ? ? ? ? inputStreamReader.close();

? ? ? ? ? ? ? ? }


? ? ? ? ? ? ? ? if (inputStream != null) {

? ? ? ? ? ? ? ? ? ? inputStream.close();

? ? ? ? ? ? ? ? }


? ? ? ? ? ? }

? ? ? ? ? ? return resultBuffer.toString();

? ? ? ? }

? ? ? ? private URLConnection openConnection(URL localURL) throws IOException {

? ? ? ? ? ? URLConnection connection;

? ? ? ? ? ? if (proxyHost != null && proxyPort != null) {

? ? ? ? ? ? ? ? Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));

? ? ? ? ? ? ? ? connection = localURL.openConnection(proxy);

? ? ? ? ? ? } else {

? ? ? ? ? ? ? ? connection = localURL.openConnection();

? ? ? ? ? ? }

? ? ? ? ? ? return connection;

? ? ? ? }


? ? ? ? /**

? ? ? ? * Render request according setting

? ? ? ? * @param request

? ? ? ? */

? ? ? ? private void renderRequest(URLConnection connection) {


? ? ? ? ? ? if (connectTimeout != null) {

? ? ? ? ? ? ? ? connection.setConnectTimeout(connectTimeout);

? ? ? ? ? ? }


? ? ? ? ? ? if (socketTimeout != null) {

? ? ? ? ? ? ? ? connection.setReadTimeout(socketTimeout);

? ? ? ? ? ? }


? ? ? ? }

? ? ? ? /*

? ? ? ? * Getter & Setter

? ? ? ? */

? ? ? ? public Integer getConnectTimeout() {

? ? ? ? ? ? return connectTimeout;

? ? ? ? }

? ? ? ? public void setConnectTimeout(Integer connectTimeout) {

? ? ? ? ? ? this.connectTimeout = connectTimeout;

? ? ? ? }

? ? ? ? public Integer getSocketTimeout() {

? ? ? ? ? ? return socketTimeout;

? ? ? ? }

? ? ? ? public void setSocketTimeout(Integer socketTimeout) {

? ? ? ? ? ? this.socketTimeout = socketTimeout;

? ? ? ? }

? ? ? ? public String getProxyHost() {

? ? ? ? ? ? return proxyHost;

? ? ? ? }

? ? ? ? public void setProxyHost(String proxyHost) {

? ? ? ? ? ? this.proxyHost = proxyHost;

? ? ? ? }

? ? ? ? public Integer getProxyPort() {

? ? ? ? ? ? return proxyPort;

? ? ? ? }

? ? ? ? public void setProxyPort(Integer proxyPort) {

? ? ? ? ? ? this.proxyPort = proxyPort;

? ? ? ? }

? ? ? ? public String getCharset() {

? ? ? ? ? ? return charset;

? ? ? ? }

? ? ? ? public void setCharset(String charset) {

? ? ? ? ? ? this.charset = charset;

? ? ? ? }

}

```

controller,這里就是工具類的使用方法了,沒什么難度,簡單的調用

```

// 獲取信息

@ResponseBody

@RequestMapping("getOpenid")

public void getOpenid(HttpServletRequest request,

HttpServletResponse response) throws Exception {

request.setCharacterEncoding("UTF-8");

response.setCharacterEncoding("UTF-8");

//需要使用小程序傳過來的js_code獲取session_key

String js_code = request.getParameter("js_code");

//這個就是要解密的東西--用戶敏感信息加密數據

String encryptedData = request.getParameter("encryptedData");

//加密算法的初始向量

String iv = request.getParameter("iv");

//調用工具類中獲取session_key的方法

String sessionkey = new GetOpenid().get(js_code);

//調用工具類中的解密方法,然后返回給小程序就OK了

JSONObject obj = new GetOpenid().getUserInfo(encryptedData, sessionkey,

iv);

Gson gson = new Gson();

String json = gson.toJson(obj);

PrintWriter pw = response.getWriter();

pw.write(json);

pw.close();

}

```

最后是小程序端的請求代碼

```

var that = this

? ? wx.login({

? ? ? success: function (res) {

? ? ? ? if (res.code) {

? ? ? ? ? wx.getUserInfo({

? ? ? ? ? ? success: datas => {

? ? ? ? ? ? ? wx.request({

? ? ? ? ? ? ? ? url: that.baseurl + 'getOpenid',

? ? ? ? ? ? ? ? data: {

? ? ? ? ? ? ? ? ? js_code: res.code,

? ? ? ? ? ? ? ? ? encryptedData: datas.encryptedData,

? ? ? ? ? ? ? ? ? iv: datas.iv

? ? ? ? ? ? ? ? },

? ? ? ? ? ? ? ? header: {

? ? ? ? ? ? ? ? ? 'content-type': 'application/json'

? ? ? ? ? ? ? ? },

? ? ? ? ? ? ? ? success: function (e) {

? ? ? ? ? ? ? ? ? console.log(e.data)

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? })

? ? ? ? ? ? }

? ? ? ? ? })

? ? ? ? }

? ? ? ? else {

? ? ? ? ? console.log('獲取用戶登錄態失敗!' + res.errMsg)

? ? ? ? }

? ? ? }

? ? })

```

大功告成!!!

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。