在Java中,可以使用`javax.crypto`包中的类来实现文件加密。下面是一个使用AES算法加密和解密文件的示例代码:
```java
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileEncryptor {
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = ALGORITHM + "/ECB/PKCS5Padding";
public static void main(String[] args) {
String inputFile = "path/to/input/file.txt";
String outputFile = "path/to/output/encrypted/file.txt";
String key = "yourKey123"; // 128位密钥
try {
// 加密文件
encryptFile(key, new File(inputFile), new File(outputFile));
System.out.println("文件加密成功!");
// 解密文件
decryptFile(key, new File(outputFile), new File("path/to/output/decrypted/file.txt"));
System.out.println("文件解密成功!");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void encryptFile(String key, File inputFile, File outputFile) throws Exception {
Key secretKey = generateKey(key);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
try (FileInputStream fis = new FileInputStream(inputFile);
FileOutputStream fos = new FileOutputStream(outputFile);
CipherOutputStream cos = new CipherOutputStream(fos, cipher)) {
byte[] buffer = new byte;
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
cos.write(buffer, 0, bytesRead);
}
}
}
public static void decryptFile(String key, File inputFile, File outputFile) throws Exception {
Key secretKey = generateKey(key);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
try (FileInputStream fis = new FileInputStream(inputFile);
CipherInputStream cis = new CipherInputStream(fis, cipher);
FileOutputStream fos = new FileOutputStream(outputFile)) {
byte[] buffer = new byte;
int bytesRead;
while ((bytesRead = cis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
}
}
private static Key generateKey(String key) throws Exception {
byte[] keyBytes = key.getBytes();
if (keyBytes.length != 16 && keyBytes.length != 24 && keyBytes.length != 32) {
throw new IllegalArgumentException("密钥长度必须是128位、192位或256位");
}
return new SecretKeySpec(keyBytes, "AES");
}
}
```
代码说明:
加密文件 (`encryptFile` 方法) :使用 `KeyGenerator` 生成一个AES密钥。
创建一个 `Cipher` 对象并设置加密模式为 `Cipher.ENCRYPT_MODE`。
使用 `CipherOutputStream` 将加密后的数据写入输出文件。
解密文件 (`decryptFile` 方法)
:
使用 `KeyGenerator` 生成一个AES密钥。
创建一个 `Cipher` 对象并设置解密模式为 `Cipher.DECRYPT_MODE`。
使用 `CipherInputStream` 读取加密文件并解密,然后将解密后的数据写入输出文件。
生成密钥 (`generateKey` 方法):
将用户提供的密钥字符串转换为字节数组,并确保其长度为128位、192位或256位。
使用 `SecretKeySpec` 类创建一个 `SecretKey` 对象。
注意事项:
密钥管理: 在实际应用中,密钥的管理非常重要。建议将密钥存储在安全的地方,而不是硬编码在代码中。 加密模式