悠悠楠杉
用Java实现AES加密解密的完整指南:从原理到实战
一、AES算法核心原理
AES(Advanced Encryption Standard)作为目前最流行的对称加密算法,其核心是通过分组密码方式对数据进行加密。与RSA不同,AES使用同一个密钥进行加密和解密,因此密钥管理尤为关键。
算法主要特点:
- 固定块大小:128位(16字节)
- 可变密钥长度:支持128/192/256位
- 多轮加密:根据密钥长度10/12/14轮
- 四种操作:SubBytes、ShiftRows、MixColumns、AddRoundKey
二、Java实现完整代码
java
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;
public class AESUtil {
// 算法/模式/填充方式
private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
/**
* 生成AES密钥(256位)
*/
public static String generateKey() throws Exception {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256, new SecureRandom());
SecretKey secretKey = keyGen.generateKey();
return Base64.getEncoder().encodeToString(secretKey.getEncoded());
}
/**
* 加密方法
*/
public static String encrypt(String data, String base64Key) throws Exception {
byte[] raw = Base64.getDecoder().decode(base64Key);
SecretKeySpec keySpec = new SecretKeySpec(raw, "AES");
// CBC模式需要IV参数
byte[] iv = new byte[16];
new SecureRandom().nextBytes(iv);
IvParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
byte[] combined = new byte[iv.length + encrypted.length];
System.arraycopy(iv, 0, combined, 0, iv.length);
System.arraycopy(encrypted, 0, combined, iv.length, encrypted.length);
return Base64.getEncoder().encodeToString(combined);
}
/**
* 解密方法
*/
public static String decrypt(String encryptedData, String base64Key) throws Exception {
byte[] combined = Base64.getDecoder().decode(encryptedData);
byte[] iv = new byte[16];
byte[] encrypted = new byte[combined.length - iv.length];
System.arraycopy(combined, 0, iv, 0, iv.length);
System.arraycopy(combined, iv.length, encrypted, 0, encrypted.length);
byte[] raw = Base64.getDecoder().decode(base64Key);
SecretKeySpec keySpec = new SecretKeySpec(raw, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
return new String(cipher.doFinal(encrypted), StandardCharsets.UTF_8);
}
}
三、关键点解析
模式选择:
- 选择CBC模式而非ECB,因为ECB会导致相同明文块产生相同密文块,存在安全隐患
- 需要初始化向量(IV)增加随机性,每次加密都应生成新IV
填充处理:
- PKCS5Padding是Java最常用的填充方式
- 当数据不是块大小的整数倍时自动填充
密钥管理:
- 示例中使用Base64编码存储密钥
- 实际项目中应考虑使用密钥管理系统(如AWS KMS)
异常处理:
- 需处理InvalidKeyException、BadPaddingException等
- 建议在业务层统一封装加密异常
四、实际应用示例
java
public class Main {
public static void main(String[] args) {
try {
// 1. 生成密钥(实际项目应安全存储)
String secretKey = AESUtil.generateKey();
System.out.println("密钥:" + secretKey);
// 2. 加密数据
String originText = "敏感数据123";
String encrypted = AESUtil.encrypt(originText, secretKey);
System.out.println("加密结果:" + encrypted);
// 3. 解密验证
String decrypted = AESUtil.decrypt(encrypted, secretKey);
System.out.println("解密结果:" + decrypted);
} catch (Exception e) {
e.printStackTrace();
}
}
}
五、性能与安全建议
线程安全:
- Cipher实例不是线程安全的,每次加密都应新建实例
- 可以考虑使用ThreadLocal优化
性能优化:
- 大量数据加密时可用AES-NI硬件加速
- 考虑缓存SecretKeySpec对象
增强安全:
- 结合HMAC进行完整性验证
- 定期轮换加密密钥
- 敏感数据加密后仍需控制数据库访问权限