小編給大家分享一下微信小程序如何實現(xiàn)用戶數(shù)據(jù)解密,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
創(chuàng)新互聯(lián)專注于企業(yè)全網(wǎng)營銷推廣、網(wǎng)站重做改版、紅旗網(wǎng)站定制設(shè)計、自適應(yīng)品牌網(wǎng)站建設(shè)、H5高端網(wǎng)站建設(shè)、成都做商城網(wǎng)站、集團公司官網(wǎng)建設(shè)、成都外貿(mào)網(wǎng)站建設(shè)、高端網(wǎng)站制作、響應(yīng)式網(wǎng)頁設(shè)計等建站業(yè)務(wù),價格優(yōu)惠性價比高,為紅旗等各大城市提供網(wǎng)站開發(fā)制作服務(wù)。
微信小程序 用戶數(shù)據(jù)解密
官方指引圖:

引導(dǎo)圖一步一步操作
1、獲取code
onLoad: function (options) {
// 頁面初始化 options為頁面跳轉(zhuǎn)所帶來的參數(shù)
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、發(fā)送code到第三方服務(wù)器,獲取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: {}, // 設(shè)置請求的 header
success: function (res) {
// success
var sessionId = res.data.session;
that.setData({ sessionId: sessionId })
wx.setStorageSync('sessionId', sessionId)
that.decodeUserInfo()
}
})
}3、在第三方服務(wù)器上發(fā)送appid、appsecret、code到微信服務(wù)器換取session_key和openid
這里使用JFinal搭建的服務(wù)器
redis配置
public void configPlugin(Plugins me) {
//用于緩存userinfo模塊的redis服務(wù)
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";
//執(zhí)行命令生成3rd_session
String session = ExecLinuxCMDUtil.instance.exec("cat /dev/urandom |od -x | tr -d ' '| head -n 1").toString();
json.put("session", session);
//創(chuàng)建默認的httpClient實例
CloseableHttpClient httpClient = getHttpClient();
try {
//用get方法發(fā)送http請求
HttpGet get = new HttpGet(url);
System.out.println("執(zhí)行g(shù)et請求:...." + get.getURI());
CloseableHttpResponse httpResponse = null;
//發(fā)送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環(huán)境下執(zhí)行l(wèi)inux命令,然后返回命令返回值。
* 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、解密用戶數(shù)據(jù)
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: {}, // 設(shè)置請求的 header
success: function (res) {
// success
console.log(res)
}
})
}console輸出結(jié)果:

后端解密代碼
/**
* 解密用戶敏感數(shù)據(jù)
*/
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;
}
}以上是“微信小程序如何實現(xiàn)用戶數(shù)據(jù)解密”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學習更多知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
分享題目:微信小程序如何實現(xiàn)用戶數(shù)據(jù)解密
文章鏈接:http://www.chinadenli.net/article2/iigooc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計、網(wǎng)站收錄、商城網(wǎng)站、云服務(wù)器、網(wǎng)站設(shè)計公司、網(wǎng)站排名
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)