酷代码 AI
菜单
服务商
DeepSeek字节豆包讯飞星火
更多选项

Java 实现:超详细 AES 加密工具类及使用示例

以下是一个使用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); ``` ######[AI写代码神器 | 496点数解答 | 2023-12-21 14:41:10]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]