在现代软件开发中,Java AES加密 是保障数据安全的重要手段。AES(Advanced Encryption Standard,高级加密标准)是一种广泛使用的对称加密算法,具有高安全性、高效率的特点。本教程将带你从零开始,用 Java 实现 AES 加密与解密,即使你是编程小白也能轻松上手!
AES 是一种对称加密算法,意味着加密和解密使用同一个密钥。它支持 128、192 和 256 位的密钥长度,其中 128 位在大多数场景下已足够安全。Java 提供了内置的加密库(javax.crypto),让我们可以轻松调用 AES 算法。
确保你已安装 JDK(建议 JDK 8 或更高版本),并配置好开发环境(如 IntelliJ IDEA 或 Eclipse)。不需要额外依赖,Java 标准库已包含所需类。
下面是一个完整的 Java 类,演示如何使用 AES/CBC/PKCS5Padding 模式进行加密和解密。我们还会处理密钥生成、Base64 编码等细节。
import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import javax.crypto.SecretKey;import javax.crypto.spec.IvParameterSpec;import javax.crypto.spec.SecretKeySpec;import java.util.Base64;public class AesUtil { // 生成AES密钥(128位) public static SecretKey generateKey() throws Exception { KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); // 128位密钥 return keyGen.generateKey(); } // 使用AES加密数据 public static String encrypt(String data, SecretKey key) throws Exception { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); // 生成随机IV(初始化向量) byte[] iv = new byte[16]; // 实际项目中应使用 SecureRandom 生成 IvParameterSpec ivSpec = new IvParameterSpec(iv); cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec); byte[] encrypted = cipher.doFinal(data.getBytes()); // 将IV和密文拼接后Base64编码 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); } // 使用AES解密数据 public static String decrypt(String encryptedData, SecretKey key) throws Exception { byte[] combined = Base64.getDecoder().decode(encryptedData); // 提取IV(前16字节) byte[] iv = new byte[16]; System.arraycopy(combined, 0, iv, 0, iv.length); // 提取密文 byte[] encrypted = new byte[combined.length - iv.length]; System.arraycopy(combined, iv.length, encrypted, 0, encrypted.length); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec ivSpec = new IvParameterSpec(iv); cipher.init(Cipher.DECRYPT_MODE, key, ivSpec); byte[] decrypted = cipher.doFinal(encrypted); return new String(decrypted); } // 测试方法 public static void main(String[] args) { try { SecretKey key = generateKey(); String originalText = "Hello, 这是一段需要加密的中文文本!"; System.out.println("原文:" + originalText); String encrypted = encrypt(originalText, key); System.out.println("加密后:" + encrypted); String decrypted = decrypt(encrypted, key); System.out.println("解密后:" + decrypted); } catch (Exception e) { e.printStackTrace(); } }}
KeyGenerator 生成 128 位 AES 密钥。AES/CBC/PKCS5Padding,其中 CBC 模式比 ECB 更安全,PKCS5Padding 是填充方式。SecureRandom 生成随机 IV,并随密文一起存储/传输。在真实项目中,请注意以下几点:
通过本教程,你已经掌握了 Java AES加密 的基本用法,理解了 AES算法实现 的核心步骤,并学会了如何编写安全的 Java安全加密 代码。无论你是开发 Web 应用、移动后端还是桌面程序,这个 对称加密教程 都能为你提供实用参考。
现在就动手试试吧!如有疑问,欢迎在评论区交流。
本文由主机测评网于2025-12-04发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025122631.html