chenjiahe
2022-02-09 3477046445264ab06bb66972aca69566caa11ae1
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
75
76
77
package com.hx.mp.util;
 
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import net.sf.json.JSONObject;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import java.io.UnsupportedEncodingException;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
 
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;
 
 
public class WechatUtil {
    public static boolean initialized = false;
 
    //log4j日志
    private static Logger logger = LoggerFactory.getLogger(WechatUtil.class.getName());
    
    public static JSONObject encryptedData(String encryptedData, String session_key, String iv) throws Exception {
        JSONObject encrypted_obj = null;
         byte[] resultByte  =decrypt(Base64.decode(encryptedData),
                 Base64.decode(session_key),
                 Base64.decode(iv));
             if(null != resultByte && resultByte.length > 0){
                 String userInfo = new String(resultByte, "UTF-8");
                 encrypted_obj = JSONObject.fromObject(userInfo);
             }else{
                 logger.error("获取unionid解密失败:encryptedData="+encryptedData+";session_key="+session_key+";iv="+iv);
             }
        return encrypted_obj;
    }
 
 
    /** 
     * AES解密 
     * @param content 密文 
     * @return 
     * @throws InvalidAlgorithmParameterException  
     * @throws NoSuchProviderException  
     */  
    public static byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte) throws Exception {
        initialize();
        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;
    }    
 
    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;    
    }     
 
 
}