package com.jst.dc.biz.util;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.SecureRandom;
/**
* @author 犀角
* @date 2019/10/29 10:29
* @description AES 对称算法加密、解密工具类
*/
public class AESUtils {
/** 秘钥长度:128,192 or 256 */
private static final int KEY_SIZE = 128;
/** 加密、解密算法名称 */
private static final String ALGORITHM = "AES";
/** 随机数生成器(RNG)算法名称 */
private static final String RNG_ALGORITHM = "SHA1PRNG";
/**
* 生成秘钥对象
*/
private static SecretKey generateKey(byte[] key) throws Exception {
// 创建安全随机数生成器
SecureRandom random = SecureRandom.getInstance(RNG_ALGORITHM);
// 设置秘钥Key的字节数组作为安全随机数生成器的种子
random.setSeed(key);
// 创建AES算法生成器
KeyGenerator gen = KeyGenerator.getInstance(ALGORITHM);
// 初始化算法生成器
gen.init(KEY_SIZE, random);
// 生成AES秘钥对象,也可以直接创建秘钥对象
return gen.generateKey();
}
/**
* 数据加密:明文->密文
*/
public static byte[] encrypt(byte[] plainBytes, byte[] key) throws Exception {
// 生成秘钥对象
SecretKey secKey = generateKey(key);
// 获取AES密码器
Cipher cipher = Cipher.getInstance(ALGORITHM);
// 初始化密码器(加密模型)
cipher.init(Cipher.ENCRYPT_MODE,secKey);
// 加密数据,返回密文
byte[] cipherBytes = cipher.doFinal(plainBytes);
return cipherBytes;
}
/**
* 数据解密:密文->明文
*/
public static byte[] decrypt(byte[] cipherBytes, byte[] key) throws Exception {
// 生成秘钥对象
SecretKey secretKey = generateKey(key);
// 获取AES密码器
Cipher cipher = Cipher.getInstance(ALGORITHM);
// 初始化密码器(解密模型)
cipher.init(Cipher.DECRYPT_MODE,secretKey);
// 解密数据,返回明文
byte[] plainBytes = cipher.doFinal(cipherBytes);
return plainBytes;
}
}