aes加密在java中通过密钥进行数据加密和解密。1. 选择密钥长度时,128位适用于大多数场景,高安全性需求可选192位或256位;2. 处理大文件需分块加密,使用cipher.update()处理数据块,cipher.dofinal()处理剩余数据;3. 密钥管理方式包括keystore、hsm、kms、pbkdf2和ecdh,根据安全需求和预算选择。
AES加密解密在Java里其实挺常见的,简单来说,就是用一个密钥把数据变成乱码,然后再用同样的密钥还原回去。用得好的话,能有效保护数据安全。
直接上代码,先看怎么用AES加密解密字符串:
import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.NoSuchAlgorithmException; import java.util.Base64; public class AESUtil { private static final String ALGORITHM = "AES"; private static final int KEY_SIZE = 128; // 可以是 128, 192, 或 256 // 生成密钥 public static SecretKey generateKey() throws NoSuchAlgorithmException { KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM); keyGenerator.init(KEY_SIZE); return keyGenerator.generateKey(); } // 密钥转为Base64字符串(方便存储和传输) public static String secretKeyToBase64(SecretKey secretKey) { byte[] encoded = secretKey.getEncoded(); return Base64.getEncoder().encodeToString(encoded); } // Base64字符串转回密钥 public static SecretKey base64ToSecretKey(String base64Key) { byte[] decodedKey = Base64.getDecoder().decode(base64Key); return new SecretKeySpec(decodedKey, 0, decodedKey.length, ALGORITHM); } // 加密 public static String encrypt(String data, SecretKey secretKey) throws Exception { Cipher cipher = Cipher.getInstance(ALGORITHM); 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, SecretKey secretKey) throws Exception { Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decodedBytes = Base64.getDecoder().decode(encryptedData); byte[] decryptedBytes = cipher.doFinal(decodedBytes); return new String(decryptedBytes, StandardCharsets.UTF_8); } public static void main(String[] args) throws Exception { SecretKey secretKey = generateKey(); String originalString = "This is a secret message!"; String encryptedString = encrypt(originalString, secretKey); String decryptedString = decrypt(encryptedString, secretKey); System.out.println("Original String: " + originalString); System.out.println("Encrypted String: " + encryptedString); System.out.println("Decrypted String: " + decryptedString); // 密钥的Base64存储示例 String base64Key = secretKeyToBase64(secretKey); System.out.println("Secret Key (Base64): " + base64Key); SecretKey restoredKey = base64ToSecretKey(base64Key); System.out.println("Restored Key equals Original Key: " + secretKey.equals(restoredKey)); } }
AES密钥长度通常有128位、192位和256位三种选择。密钥越长,安全性越高,但同时计算复杂度也会增加。128位密钥对于大多数应用来说已经足够安全。 如果你的数据安全性要求非常高,例如需要保护银行交易信息或国家机密,那么可以考虑使用192位或256位密钥。密钥长度的选择需要在安全性和性能之间进行权衡。一般来说,128位密钥是一个不错的折中方案。
立即学习“Java免费学习笔记(深入)”;
直接把整个大文件读到内存里加密肯定不行,容易OOM。 正确姿势是分块加密。
import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; public class AESFileUtil { private static final String ALGORITHM = "AES"; private static final int KEY_SIZE = 128; private static final int BUFFER_SIZE = 8192; // 8KB 缓冲区 public static SecretKey generateKey() throws NoSuchAlgorithmException { KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM); keyGenerator.init(KEY_SIZE); return keyGenerator.generateKey(); } public static void encryptFile(String inputFile, String outputFile, SecretKey secretKey) throws Exception { try (FileInputStream fis = new FileInputStream(inputFile); FileOutputStream fos = new FileOutputStream(outputFile)) { Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead; while ((bytesRead = fis.read(buffer)) != -1) { byte[] output = cipher.update(buffer, 0, bytesRead); if (output != null) { fos.write(output); } } byte[] outputBytes = cipher.doFinal(); // 处理剩余数据 if (outputBytes != null) { fos.write(outputBytes); } } } public static void decryptFile(String inputFile, String outputFile, SecretKey secretKey) throws Exception { try (FileInputStream fis = new FileInputStream(inputFile); FileOutputStream fos = new FileOutputStream(outputFile)) { Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead; while ((bytesRead = fis.read(buffer)) != -1) { byte[] output = cipher.update(buffer, 0, bytesRead); if (output != null) { fos.write(output); } } byte[] outputBytes = cipher.doFinal(); // 处理剩余数据 if (outputBytes != null) { fos.write(outputBytes); } } } public static void main(String[] args) throws Exception { SecretKey secretKey = generateKey(); String inputFile = "original.txt"; // 替换成你的输入文件 String encryptedFile = "encrypted.txt"; String decryptedFile = "decrypted.txt"; // 创建一个示例文件 try (FileOutputStream fos = new FileOutputStream(inputFile)) { fos.write("This is a sample file for encryption.".getBytes()); } encryptFile(inputFile, encryptedFile, secretKey); System.out.println("File encrypted successfully!"); decryptFile(encryptedFile, decryptedFile, secretKey); System.out.println("File decrypted successfully!"); } }
核心在于cipher.update()和cipher.doFinal()这两个方法。update()方法用于处理分块数据,而doFinal()方法用于处理最后一块数据,完成加密或解密过程。
当然有。直接在代码里写死密钥或者简单存储SecretKey是很不安全的。 常见的密钥管理方式包括:
选择哪种密钥管理方式取决于你的安全需求和预算。一般来说,对于高安全性的应用,建议使用HSM或KMS。对于安全性要求较低的应用,可以使用KeyStore或PBKDF2。
以上就是Java中如何用AES实现数据加密解密的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号