guang
2023-08-01 6fb44f4051509f66cc887d18469e2947e3702c11
提交 | 用户 | age
5c5945 1 package com.hx.mp.util;
E 2
3 import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
4 import net.sf.json.JSONObject;
5 import org.bouncycastle.jce.provider.BouncyCastleProvider;
6 import org.slf4j.Logger;
7 import org.slf4j.LoggerFactory;
8
9 import java.io.UnsupportedEncodingException;
10 import java.security.AlgorithmParameters;
11 import java.security.InvalidAlgorithmParameterException;
12 import java.security.InvalidKeyException;
13 import java.security.Key;
14 import java.security.NoSuchAlgorithmException;
15 import java.security.NoSuchProviderException;
16 import java.security.Security;
17
18 import javax.crypto.BadPaddingException;
19 import javax.crypto.Cipher;
20 import javax.crypto.IllegalBlockSizeException;
21 import javax.crypto.NoSuchPaddingException;
22 import javax.crypto.spec.IvParameterSpec;
23 import javax.crypto.spec.SecretKeySpec;
24  
25  
26 public class WechatUtil {
27     public static boolean initialized = false;
28
29     //log4j日志
30     private static Logger logger = LoggerFactory.getLogger(WechatUtil.class.getName());
31     
32     public static JSONObject encryptedData(String encryptedData, String session_key, String iv) throws Exception {
33         JSONObject encrypted_obj = null;
34          byte[] resultByte  =decrypt(Base64.decode(encryptedData),
35                  Base64.decode(session_key),
36                  Base64.decode(iv));
37              if(null != resultByte && resultByte.length > 0){
38                  String userInfo = new String(resultByte, "UTF-8");
39                  encrypted_obj = JSONObject.fromObject(userInfo);
40              }else{
41                  logger.error("获取unionid解密失败:encryptedData="+encryptedData+";session_key="+session_key+";iv="+iv);
42              }
43         return encrypted_obj;
44     }
45
46
47     /** 
48      * AES解密 
49      * @param content 密文 
50      * @return 
51      * @throws InvalidAlgorithmParameterException  
52      * @throws NoSuchProviderException  
53      */  
54     public static byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte) throws Exception {
55         initialize();
56         Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
57         Key sKeySpec = new SecretKeySpec(keyByte, "AES");
58
59         cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(ivByte));// 初始化
60         byte[] result = cipher.doFinal(content);
61         return result;
62     }    
63
64     public static void initialize(){
65         if (initialized) return;
66         Security.addProvider(new BouncyCastleProvider());
67         initialized = true;
68     }
69     //生成iv    
70     public static AlgorithmParameters generateIV(byte[] iv) throws Exception{    
71         AlgorithmParameters params = AlgorithmParameters.getInstance("AES");    
72         params.init(new IvParameterSpec(iv));    
73         return params;    
74     }     
75  
76  
77 }