记录一个工具AES加密



import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
/**
* AES秘钥工具类
*/
public class AESUtils {
/**
*加密器
*/
private static final KeyGenerator KEY_GENERATOR =
ThreadLocal.withInitial(() -> {
try {
return KeyGenerator.getInstance("AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}).get();
/**
*密码解析器
*/
    private static final  Cipher CIPHER = ThreadLocal.withInitial(() -> {
try {
return Cipher.getInstance("AES");
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
e.printStackTrace();
}
return null;
}).get();


/**
*
* AES加密字符串
* 只限于对称加密
* 这个方法加密的数据是使用字符串的utf-8格式的字符数组进行加密的
* @param content 需要被加密的字符串
* @param password 加密需要的密码
* @return 密文,当出现异常时return null
*/
public static byte[] encrypt(String content, String password){
try {
// 利用被加密数据作为随机数初始化出
// 256位的key生产者 SecureRandom是生成安全随机数序列,
//password是种子,只要password没有改变,就能解密出来
KEY_GENERATOR.init(256, new SecureRandom(password.getBytes()));
//转换为AES密钥
//初始化为加密模式的密码器
//KEY_GENERATOR.generateKey()生成一个密钥
//getEncoded()返回基本编码格式的密钥,如果此密钥不支持编码,则返回null。
CIPHER.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(KEY_GENERATOR.generateKey().getEncoded(), "AES"));
//获取加密数据字符数组,设置编码集,加密
byte[] result = CIPHER.doFinal(content.getBytes("utf-8"));
return result;
}catch (UnsupportedEncodingException e) {
System.err.println("加密错误,获取加密数据");
e.printStackTrace();
} catch (InvalidKeyException e) {
System.err.println("加密错误,初始化为加密模式的密码器错误");
e.printStackTrace();
}catch (BadPaddingException e) {
System.err.println("加密错误,一个导致错误的参数被传入了");
e.printStackTrace();
} catch (IllegalBlockSizeException e){
System.err.println("加密错误,传入的字符数组不存在");
e.printStackTrace();
}
return null;
}

/**
* 解密AES加密过的字符串
* 只限于对称加密
* @param content AES加密过的内容
* @param password 加密时的密码
* @return 明文
*/
public static byte[] decrypt(byte[] content, String password) {
if (content.length<1)return null;
try {
KEY_GENERATOR.init(256, new SecureRandom(password.getBytes()));
//转换为AES专用密钥后,初始化为解密模式的密码器
//KEY_GENERATOR.generateKey().getEncoded()返回基本编码格式的密钥
CIPHER.init(Cipher.DECRYPT_MODE,new SecretKeySpec(KEY_GENERATOR.generateKey().getEncoded(), "AES"));
return CIPHER.doFinal(content);
}catch (InvalidKeyException e) {
System.err.println("解密错误,密码解析器初始化失败,抛出异常");
e.printStackTrace();
}catch (IllegalBlockSizeException e) {
System.err.println("解密错误,密码解析错误,模拟数字转换错误,抛出异常");
e.printStackTrace();
}catch (BadPaddingException e) {
System.err.println("解密错误,密码解析错误,错误的填充数据,抛出异常");
e.printStackTrace();
}
return null;
}
}
posted @ 2019-12-09 10:31  月一弯  阅读(190)  评论(0)    收藏  举报