以下是一个使用Java编写的AES加密工具类示例: ```java import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.util.Base64; public class AESUtils { private static final String AES_ALGORITHM = "AES"; private static final String AES_PADDING_MODE = "AES/ECB/PKCS5Padding"; public static String encrypt(String data, String key) throws Exception { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), AES_ALGORITHM); Cipher cipher = Cipher.getInstance(AES_PADDING_MODE); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(encryptedBytes); } public static String decrypt(String encryptedData, String key) throws Exception { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), AES_ALGORITHM); Cipher cipher = Cipher.getInstance(AES_PADDING_MODE); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData)); return new String(decryptedBytes, StandardCharsets.UTF_8); } } ``` 使用示例: ```java public class Main { public static void main(String[] args) { try { String key = "ThisIsASecretKey"; String data = "Hello, World!"; String encryptedData = AESUtils.encrypt(data, key); System.out.println("Encrypted Data: " + encryptedData); String decryptedData = AESUtils.decrypt(encryptedData, key); System.out.println("Decrypted Data: " + decryptedData); } catch (Exception e) { e.printStackTrace(); } } } ``` 请确保在使用此代码时遵守适用的法律和安全规定。这只是一个基本示例,实际使用中可能需要更多的参数验证和错误处理。 [2023-12-21 14:39:17 | AI写代码神器 | 1865点数解答]