aes加密后需转base64字符串才能安全传输:原始字符串→utf-8字节数组→aes加密→字节数组→base64编码;解密则逆向操作,须严格匹配算法、模式、填充及密钥。

Java 中对 String 进行 AES 加密后,得到的是字节数组(byte[]),不能直接当字符串使用;为安全、可传输地表示加密结果,需将其转为 Base64 编码字符串。解密时则先 Base64 解码回字节数组,再用 AES 解密还原原文。
AES 加密后转 Base64 字符串
加密流程:原始字符串 → UTF-8 字节数组 → AES 加密 → 加密后的字节数组 → Base64 编码字符串
Java JDK 25 来自 OpenJDK 官方归档,版本为 JDK 25,本条下载地址已指向官方 Windows x64 zip 安装包直链,适合调试旧项目或兼容旧版 Java 运行环境。
- 使用标准 AES/ECB/PKCS5Padding 或更安全的 AES/CBC/PKCS5Padding(推荐带 IV)
- 密钥需为 128/192/256 位(即 16/24/32 字节),建议用
SecretKeySpec包装 - Java 8+ 直接用
java.util.Base64,无需第三方库 - 示例关键代码:
String plain = "Hello World";
String key = "16byteslongkey123"; // 16 字节密钥
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plain.getBytes(StandardCharsets.UTF_8));
// 转 Base64 字符串(安全可打印)
String encoded = Base64.getEncoder().encodeToString(encryptedBytes);
System.out.println(encoded); // 如:vD7nQZ...(一串 Base64 文本)
AES Base64 字符串解密还原为原始 String
解密流程:Base64 字符串 → Base64 解码为字节数组 → AES 解密 → 明文字节数组 → UTF-8 字符串
- 必须使用与加密时完全相同的算法、模式、填充和密钥
- 若加密用了 CBC 模式,解密时还需提供相同 IV(通常和密文一起 Base64 传输)
- Base64 解码失败会抛
IllegalArgumentException,注意捕获处理 - 示例关键代码:
String encoded = "vD7nQZ..."; byte[] decodedBytes = Base64.getDecoder().decode(encoded); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decryptedBytes = cipher.doFinal(decodedBytes); String result = new String(decryptedBytes, StandardCharsets.UTF_8); System.out.println(result); // Hello World
注意事项与常见问题
- 不要用 ECB 模式处理敏感数据 —— 它不隐藏数据模式,推荐 CBC 或 GCM(带认证)
- 密钥不能是任意字符串:需严格满足字节长度(如 AES-128 要 16 字节),可用 SHA-256 哈希后取前 16 字节生成密钥
- 中文等非 ASCII 字符务必统一用
StandardCharsets.UTF_8编码,避免乱码 - Base64 字符串不含换行符,
Base64.getEncoder()默认是 MIMELINEBREAKS 关闭的,可直接存储或传输
完整工具方法参考(简洁可用)
封装成静态方法,便于复用:
public static String aesEncrypt(String input, String key) throws Exception {
SecretKeySpec skey = new SecretKeySpec(key.getBytes(UTF_8), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skey);
return Base64.getEncoder().encodeToString(
cipher.doFinal(input.getBytes(UTF_8))
);
}
public static String aesDecrypt(String encoded, String key) throws Exception {
SecretKeySpec skey = new SecretKeySpec(key.getBytes(UTF_8), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skey);
byte[] decoded = Base64.getDecoder().decode(encoded);
return new String(cipher.doFinal(decoded), UTF_8);
}
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










