本文實例為大家分享了java解密微信小程序手機(jī)號的具體代碼,供大家參考,具體內(nèi)容如下
第一步:創(chuàng)建aes解密工具類:代碼如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
import org.apache.commons.codec.binary.base64; import javax.crypto.cipher; import javax.crypto.keygenerator; import javax.crypto.spec.ivparameterspec; import javax.crypto.spec.secretkeyspec; import java.security.algorithmparameters; import java.security.key; import java.security.security; public class aes { // 算法名 public static final string key_name = "aes" ; // 加解密算法/模式/填充方式 // ecb模式只用密鑰即可對數(shù)據(jù)進(jìn)行加密解密,cbc模式需要添加一個iv public static final string cipher_algorithm = "aes/cbc/pkcs7padding" ; /** * 微信 數(shù)據(jù)解密<br/> * 對稱解密使用的算法為 aes-128-cbc,數(shù)據(jù)采用pkcs#7填充<br/> * 對稱解密的目標(biāo)密文:encrypted=base64_decode(encryptdata)<br/> * 對稱解密秘鑰:key = base64_decode(session_key),aeskey是16字節(jié)<br/> * 對稱解密算法初始向量:iv = base64_decode(iv),同樣是16字節(jié)<br/> * * @param encrypted 目標(biāo)密文 * @param session_key 會話id * @param iv 加密算法的初始向量 */ public static string wxdecrypt(string encrypted, string session_key, string iv) { string json = null ; byte [] encrypted64 = base64.decodebase64(encrypted); byte [] key64 = base64.decodebase64(session_key); byte [] iv64 = base64.decodebase64(iv); byte [] data; try { init(); json = new string(decrypt(encrypted64, key64, generateiv(iv64))); } catch (exception e) { e.printstacktrace(); } return json; } /** * 初始化密鑰 */ public static void init() throws exception { security.addprovider( new org.bouncycastle.jce.provider.bouncycastleprovider()); keygenerator.getinstance(key_name).init( 128 ); } /** * 生成iv */ public static algorithmparameters generateiv( byte [] iv) throws exception { // iv 為一個 16 字節(jié)的數(shù)組,這里采用和 ios 端一樣的構(gòu)造方法,數(shù)據(jù)全為0 // arrays.fill(iv, (byte) 0x00); algorithmparameters params = algorithmparameters.getinstance(key_name); params.init( new ivparameterspec(iv)); return params; } /** * 生成解密 */ public static byte [] decrypt( byte [] encrypteddata, byte [] keybytes, algorithmparameters iv) throws exception { key key = new secretkeyspec(keybytes, key_name); cipher cipher = cipher.getinstance(cipher_algorithm); // 設(shè)置為解密模式 cipher.init(cipher.decrypt_mode, key, iv); return cipher.dofinal(encrypteddata); } } |
第二步:接口調(diào)用
接收參數(shù): encrypted session_key iv
1
2
3
4
5
6
|
public string decodeuserinfo(string encrypted, string session_key, string iv) throws ioexception { string json = wxdecrypt(encrypted, session_key, iv); system.out.println(json); return json; } |
官方文檔:鏈接地址
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/Elion_jia/article/details/79551781