用Java写一个文件加密与解密的基础程序
时间: 2023-09-29 20:07:23 浏览: 97
好的,以下是一个基础的Java文件加密与解密程序示例:
```java
import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class FileEncryptorDecryptor {
private Cipher ecipher;
private Cipher dcipher;
// 构造方法,传入密钥
public FileEncryptorDecryptor(SecretKey key) throws Exception {
ecipher = Cipher.getInstance("AES");
dcipher = Cipher.getInstance("AES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
}
// 加密文件方法
public void encrypt(File inputFile, File outputFile) throws Exception {
FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(outputFile);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
byte[] encryptedBytes = ecipher.update(buffer, 0, bytesRead);
outputStream.write(encryptedBytes);
}
byte[] encryptedBytes = ecipher.doFinal();
outputStream.write(encryptedBytes);
inputStream.close();
outputStream.close();
}
// 解密文件方法
public void decrypt(File inputFile, File outputFile) throws Exception {
FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(outputFile);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
byte[] decryptedBytes = dcipher.update(buffer, 0, bytesRead);
outputStream.write(decryptedBytes);
}
byte[] decryptedBytes = dcipher.doFinal();
outputStream.write(decryptedBytes);
inputStream.close();
outputStream.close();
}
public static void main(String[] args) throws Exception {
// 生成密钥
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128);
SecretKey key = keyGenerator.generateKey();
// 加密文件
FileEncryptorDecryptor encryptor = new FileEncryptorDecryptor(key);
encryptor.encrypt(new File("input.txt"), new File("encrypted.bin"));
// 解密文件
FileEncryptorDecryptor decryptor = new FileEncryptorDecryptor(key);
decryptor.decrypt(new File("encrypted.bin"), new File("decrypted.txt"));
}
}
```
这里使用了AES对称加密算法,可以根据需要选择不同的算法。需要注意的是,这里的密钥生成方式是随机生成的,实际应用中需要使用更为安全的密钥生成方式。
阅读全文