温馨提示×

java如何实现文件加密与解密

小亿
170
2023-10-13 01:32:37
栏目: 编程语言

在Java中实现文件加密与解密可以使用各种加密算法和IO流来实现。下面是一个示例代码,使用AES对称加密算法和文件IO流来实现文件的加密和解密:

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
public class FileEncryption {
public static void encrypt(String key, File inputFile, File outputFile) throws Exception {
doCrypto(Cipher.ENCRYPT_MODE, key, inputFile, outputFile);
}
public static void decrypt(String key, File inputFile, File outputFile) throws Exception {
doCrypto(Cipher.DECRYPT_MODE, key, inputFile, outputFile);
}
private static void doCrypto(int cipherMode, String key, File inputFile, File outputFile) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(cipherMode, secretKey);
FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(outputFile);
if (cipherMode == Cipher.ENCRYPT_MODE) {
CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);
writeBytes(inputStream, cipherOutputStream);
cipherOutputStream.close();
} else if (cipherMode == Cipher.DECRYPT_MODE) {
CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
writeBytes(cipherInputStream, outputStream);
cipherInputStream.close();
}
inputStream.close();
outputStream.close();
}
private static void writeBytes(InputStream inputStream, OutputStream outputStream) throws IOException {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
}
public static void main(String[] args) {
try {
File inputFile = new File("input.txt");
File encryptedFile = new File("encrypted.txt");
File decryptedFile = new File("decrypted.txt");
String key = "ThisIsASecretKey";
encrypt(key, inputFile, encryptedFile);
System.out.println("File encrypted successfully.");
decrypt(key, encryptedFile, decryptedFile);
System.out.println("File decrypted successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}

在上述代码中,我们定义了两个方法encryptdecrypt,分别用于加密和解密文件。在doCrypto方法中,我们创建了一个AES加密算法的Cipher对象,并使用一个密钥初始化该对象。然后根据加密或解密模式,使用CipherInputStreamCipherOutputStream来读取和写入文件内容。加密和解密过程中使用的密钥长度必须是16、24或32字节,所以我们使用密钥的字节数组来创建一个SecretKeySpec对象。

main方法中,我们定义了输入文件、加密后文件和解密后文件的路径,并指定一个密钥。然后调用encrypt方法对输入文件进行加密,再调用decrypt方法对加密后的文件进行解密。

请注意,这只是一个简单的示例,实际使用时需要根据具体需求进行优化和安全性考虑。

0