以下是一个使用Java实现AES加密和解密的工具类示例: ```java import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.util.Base64; public class AESUtil { private static final String ALGORITHM = "AES"; private static final String KEY_SPEC = "AES/ECB/PKCS5Padding"; public static String encrypt(String plainText, String key) throws Exception { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM); Cipher cipher = Cipher.getInstance(KEY_SPEC); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] cipherText = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(cipherText); } public static String decrypt(String cipherText, String key) throws Exception { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM); Cipher cipher = Cipher.getInstance(KEY_SPEC); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] plainText = cipher.doFinal(Base64.getDecoder().decode(cipherText)); return new String(plainText, StandardCharsets.UTF_8); } } ``` 使用示例: ```java String key = "1234567890123456"; // 16个字节的密钥 String plainText = "Hello World!"; // 待加密的明文 String cipherText = AESUtil.encrypt(plainText, key); // 加密后的密文 String decryptedText = AESUtil.decrypt(cipherText, key); // 解密后的明文 System.out.println("Plain Text: " + plainText); System.out.println("Cipher Text: " + cipherText); System.out.println("Decrypted Text: " + decryptedText); ``` [2023-12-21 14:41:10 | AI写代码神器 | 496点数解答]