使用AES算法结合CBC模式和IV实现文件加密解密,通过CipherOutputStream加密、CipherInputStream解密,密钥由KeyGenerator生成并安全存储,IV随机生成且单独保存,确保文件安全性。

在Java中实现文件的加密和解密功能,主要依赖于Java的加密扩展(Java Cryptography Extension, JCE)。常用的方式是使用对称加密算法如AES(Advanced Encryption Standard),它安全高效,适合大文件处理。下面介绍如何用AES算法实现文件的加密与解密。
AES是一种对称加密算法,加密和解密使用相同的密钥。为了保证安全性,通常结合CBC模式和PKCS5Padding填充方式,并使用随机生成的初始化向量(IV)。
以下是实现文件加密的关键步骤:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.CipherOutputStream;
import java.security.SecureRandom;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class FileEncryptor {
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";
public static void encrypt(String keyFile, String inputFile, String outputFile) throws Exception {
SecretKey key = loadOrGenerateKey(keyFile);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
byte[] iv = new byte[16];
SecureRandom random = new SecureRandom();
random.nextBytes(iv);
IvParameterSpec ivSpec = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
// 写入IV到输出文件开头
try (FileOutputStream fos = new FileOutputStream(outputFile);
FileOutputStream ivFos = new FileOutputStream(outputFile + ".iv")) {
ivFos.write(iv); // 单独保存IV
}
try (FileInputStream fis = new FileInputStream(inputFile);
CipherOutputStream cos = new CipherOutputStream(new FileOutputStream(outputFile), cipher)) {
byte[] buffer = new byte[1024];
int read;
while ((read = fis.read(buffer)) != -1) {
cos.write(buffer, 0, read);
}
}
}
}
解密过程需要原始密钥和加密时使用的IV。IV通常随加密文件一起存储(如单独文件或附加在加密文件头部)。
立即学习“Java免费学习笔记(深入)”;
public static void decrypt(String keyFile, String encryptedFile, String decryptedFile) throws Exception {
SecretKey key = loadOrGenerateKey(keyFile);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
// 读取IV
byte[] iv = new byte[16];
try (FileInputStream ivFis = new FileInputStream(encryptedFile + ".iv")) {
ivFis.read(iv);
}
IvParameterSpec ivSpec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
// 解密文件
try (FileInputStream fis = new FileInputStream(encryptedFile);
CipherInputStream cis = new CipherInputStream(fis, cipher);
FileOutputStream fos = new FileOutputStream(decryptedFile)) {
byte[] buffer = new byte[1024];
int read;
while ((read = cis.read(buffer)) != -1) {
fos.write(buffer, 0, read);
}
}
}
密钥的安全性直接决定加密系统的强度。不推荐硬编码密钥。可以采用以下方式:
基本上就这些。只要合理使用AES和IV,配合正确的输入输出流处理,就能安全地实现文件加解密。注意异常处理和资源关闭,确保大文件也能稳定运行。
以上就是如何在Java中实现文件加密解密功能的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号