You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
94 lines
2.8 KiB
94 lines
2.8 KiB
2 years ago
|
package com.fr.plugin.cmd.utils;
|
||
|
|
||
|
import com.fanruan.api.log.LogKit;
|
||
|
import com.fr.third.org.apache.commons.codec.binary.Base64;
|
||
|
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||
|
|
||
|
import javax.crypto.Cipher;
|
||
|
import javax.crypto.spec.IvParameterSpec;
|
||
|
import javax.crypto.spec.SecretKeySpec;
|
||
|
import java.security.Security;
|
||
|
|
||
|
public class AESUtil {
|
||
|
/**
|
||
|
* 密钥算法
|
||
|
*/
|
||
|
private static final String KEY_ALGORITHM = "AES";
|
||
|
|
||
|
/**
|
||
|
* 加密/解密算法 / 工作模式 / 填充方式
|
||
|
* Java 6支持PKCS5Padding填充方式
|
||
|
* Bouncy Castle支持PKCS7Padding填充方式
|
||
|
*/
|
||
|
private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS7Padding";
|
||
|
|
||
|
/**
|
||
|
* 偏移量,只有CBC模式才需要
|
||
|
*/
|
||
|
private final static String ivParameter = "xxx";
|
||
|
|
||
|
/**
|
||
|
* AES要求密钥长度为128位或192位或256位,java默认限制AES密钥长度最多128位
|
||
|
*/
|
||
|
public static String sKey = "xxx";
|
||
|
|
||
|
/**
|
||
|
* 编码格式
|
||
|
*/
|
||
|
public static final String ENCODING = "utf-8";
|
||
|
|
||
|
|
||
|
static {
|
||
|
//如果是PKCS7Padding填充方式,则必须加上下面这行
|
||
|
Security.addProvider(new BouncyCastleProvider());
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* AES加密
|
||
|
*
|
||
|
* @param source 源字符串
|
||
|
* @param key 密钥
|
||
|
* @return 加密后的密文
|
||
|
* @throws Exception
|
||
|
*/
|
||
|
public static String encrypt(String source, String key) {
|
||
|
try {
|
||
|
byte[] sourceBytes = source.getBytes(ENCODING);
|
||
|
byte[] keyBytes = key.getBytes(ENCODING);
|
||
|
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, "BC");
|
||
|
IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes(ENCODING));
|
||
|
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, KEY_ALGORITHM), iv);
|
||
|
byte[] decrypted = cipher.doFinal(sourceBytes);
|
||
|
return Base64.encodeBase64String(decrypted);
|
||
|
} catch (Exception e) {
|
||
|
e.printStackTrace();
|
||
|
}
|
||
|
return null;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* AES解密
|
||
|
*
|
||
|
* @param encryptStr 加密后的密文
|
||
|
* @param key 密钥
|
||
|
* @return 源字符串
|
||
|
* @throws Exception
|
||
|
*/
|
||
|
public static String decrypt(String encryptStr, String key) {
|
||
|
try {
|
||
|
byte[] sourceBytes = Base64.decodeBase64(encryptStr);
|
||
|
byte[] keyBytes = key.getBytes(ENCODING);
|
||
|
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, "BC");
|
||
|
IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes(ENCODING));
|
||
|
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, KEY_ALGORITHM), iv);
|
||
|
byte[] decoded = cipher.doFinal(sourceBytes);
|
||
|
return new String(decoded, ENCODING);
|
||
|
} catch (Exception e) {
|
||
|
LogKit.error(e.getMessage(), e);
|
||
|
}
|
||
|
return null;
|
||
|
}
|
||
|
|
||
|
|
||
|
}
|