企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# Java AES 加密解密示例 > 原文: [https://howtodoinjava.com/security/java-aes-encryption-example/](https://howtodoinjava.com/security/java-aes-encryption-example/) Java 支持许多安全的加密算法,但是其中一些功能较弱,无法在安全性要求很高的应用中使用。 例如,数据加密标准(DES)加密算法被认为是高度不安全的。 使用[电子前沿基金会(EFF)的 Deep Crack](https://en.wikipedia.org/wiki/EFF_DES_cracker) 之类的机器,在一天之内用 DES 加密了使用 DES 加密的邮件。 一种更安全的加密算法是 [AES](https://searchsecurity.techtarget.com/definition/Advanced-Encryption-Standard) – **高级加密标准**,它是一种对称加密算法。 美国使用 AES 加密来保护敏感但未分类的资料,因此可以说它足够安全。 > 阅读更多: [Java AES 256 加密解密示例](https://howtodoinjava.com/security/aes-256-encryption-decryption/) ## 1\. AES 加密和解密 我们来看一个在 Java 程序中使用 AES 加密的示例。 ```java import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Base64; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class AES { private static SecretKeySpec secretKey; private static byte[] key; public static void setKey(String myKey) { MessageDigest sha = null; try { key = myKey.getBytes("UTF-8"); sha = MessageDigest.getInstance("SHA-1"); key = sha.digest(key); key = Arrays.copyOf(key, 16); secretKey = new SecretKeySpec(key, "AES"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } public static String encrypt(String strToEncrypt, String secret) { try { setKey(secret); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8"))); } catch (Exception e) { System.out.println("Error while encrypting: " + e.toString()); } return null; } public static String decrypt(String strToDecrypt, String secret) { try { setKey(secret); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING"); cipher.init(Cipher.DECRYPT_MODE, secretKey); return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt))); } catch (Exception e) { System.out.println("Error while decrypting: " + e.toString()); } return null; } } ``` ## 2.加密和解密示例 让我们测试一下是否能够从加密字符串中取回解密后的字符串。 ```java public static void main(String[] args) { final String secretKey = "ssshhhhhhhhhhh!!!!"; String originalString = "howtodoinjava.com"; String encryptedString = AES.encrypt(originalString, secretKey) ; String decryptedString = AES.decrypt(encryptedString, secretKey) ; System.out.println(originalString); System.out.println(encryptedString); System.out.println(decryptedString); } ``` ```java Output: howtodoinjava.com Tg2Nn7wUZOQ6Xc+1lenkZTQ9ZDf9a2/RBRiqJBCIX6o= howtodoinjava.com ``` 在下面将您的问题和评论丢给我。 学习愉快!