Java使用AES加密

public class AESUtil {
public static final String algorithm = "AES";
// AES/CBC/NOPaddin
// AES 默认模式
// 使用CBC模式, 在初始化Cipher对象时, 需要增加参数, 初始化向量IV : IvParameterSpec iv = new
// IvParameterSpec(key.getBytes());
// NOPadding: 使用NOPadding模式时, 原文长度必须是8byte的整数倍
// PKCS5Padding: 自动填充
public static final String transformation = "AES/CBC/PKCS5Padding";
public static final String key = "1234567812345678";
/***
* 加密
* @param original 需要加密的参数(注意必须是16位)
* @return
* @throws Exception
*/
public static String encryptByAES(String original) throws Exception {
// 获取Cipher
Cipher cipher = Cipher.getInstance(transformation);
// 生成密钥
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), algorithm);
// 指定模式(加密)和密钥
// 创建初始化向量
IvParameterSpec iv = new IvParameterSpec(key.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
// cipher.init(Cipher.ENCRYPT_MODE, keySpec);
// 加密
byte[] bytes = cipher.doFinal(original.getBytes());
return encryptBASE64(bytes);
}
/**
* 解密
* @param encrypted 需要解密的参数
* @return
* @throws Exception
*/
public static String decryptByAES(String encrypted) throws Exception {
// 获取Cipher
Cipher cipher = Cipher.getInstance(transformation);
// 生成密钥
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), algorithm);
// 指定模式(解密)和密钥
// 创建初始化向量
IvParameterSpec iv = new IvParameterSpec(key.getBytes());
cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);
// cipher.init(Cipher.DECRYPT_MODE, keySpec);
// 解密
byte[] bytes = cipher.doFinal(decryBASE64(encrypted));
return new String(bytes);
}
/***
* BASE64解密
* @param key
* @return
* @throws Exception
*/
public static byte[] decryBASE64(String key) throws Exception{
return (new BASE64Decoder()).decodeBuffer(key);
}
/***
* BASE64加密
* @param key
* @return
* @throws Exception
*/
public static String encryptBASE64(byte[] key) throws Exception{
return (new BASE64Encoder()).encode(key);
}
}
posted @   鱼鱼寡欢  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示