在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();
}
}
}
在上述代碼中,我們定義了兩個方法encrypt
和decrypt
,分別用于加密和解密文件。在doCrypto
方法中,我們創建了一個AES加密算法的Cipher
對象,并使用一個密鑰初始化該對象。然后根據加密或解密模式,使用CipherInputStream
或CipherOutputStream
來讀取和寫入文件內容。加密和解密過程中使用的密鑰長度必須是16、24或32字節,所以我們使用密鑰的字節數組來創建一個SecretKeySpec
對象。
在main
方法中,我們定義了輸入文件、加密后文件和解密后文件的路徑,并指定一個密鑰。然后調用encrypt
方法對輸入文件進行加密,再調用decrypt
方法對加密后的文件進行解密。
請注意,這只是一個簡單的示例,實際使用時需要根據具體需求進行優化和安全性考慮。