在Java中,可以使用加密算法來對文件進行加密和解密。常用的加密算法包括對稱加密算法和非對稱加密算法。
對稱加密算法:使用相同的密鑰對文件進行加密和解密。常用的對稱加密算法包括AES和DES。以下是一個使用AES算法對文件進行加密和解密的示例代碼:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileEncryption {
public static void encryptFile(String inputFilePath, String outputFilePath, String key) throws Exception {
byte[] keyBytes = key.getBytes();
SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] inputFileBytes = Files.readAllBytes(Paths.get(inputFilePath));
byte[] encryptedBytes = cipher.doFinal(inputFileBytes);
FileOutputStream outputStream = new FileOutputStream(outputFilePath);
outputStream.write(encryptedBytes);
outputStream.close();
}
public static void decryptFile(String inputFilePath, String outputFilePath, String key) throws Exception {
byte[] keyBytes = key.getBytes();
SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] inputFileBytes = Files.readAllBytes(Paths.get(inputFilePath));
byte[] decryptedBytes = cipher.doFinal(inputFileBytes);
FileOutputStream outputStream = new FileOutputStream(outputFilePath);
outputStream.write(decryptedBytes);
outputStream.close();
}
public static void main(String[] args) {
String inputFilePath = "input.txt";
String outputFilePath = "output.txt";
String key = "secretKey";
try {
encryptFile(inputFilePath, outputFilePath, key);
decryptFile(outputFilePath, "decrypted.txt", key);
} catch (Exception e) {
e.printStackTrace();
}
}
}
以上示例代碼使用AES算法對文件進行加密和解密,其中secretKey是用于加密和解密的密鑰。可以根據需要調整密鑰長度和加密算法。
除了對稱加密算法,還可以使用非對稱加密算法如RSA來對文件進行加密和解密。非對稱加密算法需要一對公鑰和私鑰,公鑰用于加密數據,私鑰用于解密數據。