위챗 애플릿 사용자 데이터 복호화
16017 단어 틀 학습
위챗 애플릿 사용자 데이터 복호화
상세 설명 및 다운로드 주소
참조 링크:
공식 문서
위챗 애플릿의 사용자 데이터 복호화 (7)
공식 안내도
공식 안내도에 따라 한 걸음 한 걸음 조작하다
1. 코드 가져오기
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, 타사 서버에 코드를 전송하여 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. 제3자 서버에 appid, appsecret, 코드를 위챗 서버로 보내session_key 및 openid
JFinal이 구축한 서버를 사용합니다.
Redis 구성
public void configPlugin(Plugins me) {
// userinfo redis
RedisPlugin userInfoRedis = new RedisPlugin("userInfo","localhost");
me.add(userInfoRedis);
}
타사 세션 가져오기
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("
");
}
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;
}
}