83 lines
2.6 KiB
Java
83 lines
2.6 KiB
Java
package com.xkrs.utils;
|
||
|
||
import com.alibaba.fastjson.JSONObject;
|
||
import org.apache.tomcat.util.codec.binary.Base64;
|
||
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||
import org.springframework.stereotype.Component;
|
||
|
||
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;
|
||
|
||
/**
|
||
* 解密工具类
|
||
*
|
||
* @Author duyongmeng
|
||
* @Time 2020/11/10
|
||
*/
|
||
@Component
|
||
public class DecodeUtils {
|
||
// 算法名
|
||
public static final String KEY_NAME = "AES";
|
||
// 加解密算法/模式/填充方式
|
||
// ECB模式只用密钥即可对数据进行加密解密,CBC模式需要添加一个iv
|
||
public static final String CIPHER_ALGORITHM = "AES/CBC/PKCS7Padding";
|
||
|
||
/**
|
||
* @param encrypted 目标密文
|
||
* @param session_key 会话ID
|
||
* @param iv 加密算法的初始向量
|
||
*/
|
||
public JSONObject wxDecrypt(String encrypted, String session_key, String iv) {
|
||
String json;
|
||
JSONObject jsonObject = 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)));
|
||
jsonObject = JSONObject.parseObject(json);
|
||
} catch (Exception e) {
|
||
e.printStackTrace();
|
||
}
|
||
return jsonObject;
|
||
}
|
||
|
||
/**
|
||
* 初始化密钥
|
||
*/
|
||
public static void init() throws Exception {
|
||
Security.addProvider(new BouncyCastleProvider());
|
||
KeyGenerator.getInstance(KEY_NAME).init(128);
|
||
}
|
||
|
||
/**
|
||
* 生成iv
|
||
*/
|
||
public static AlgorithmParameters generateIV(byte[] iv) throws Exception {
|
||
// iv 为一个 16 字节的数组,这里采用和 iOS 端一样的构造方法,数据全为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);
|
||
// 设置为解密模式
|
||
cipher.init(Cipher.DECRYPT_MODE, key, iv);
|
||
return cipher.doFinal(encryptedData);
|
||
}
|
||
}
|