java实现文件加解密DES
时间: 2024-04-13 11:25:41 浏览: 166
Java中可以使用javax.crypto包中的DES算法来实现文件的加解密。下面是一个简单的示例代码:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
public class FileEncryptor {
private static final String ALGORITHM = "DES";
private static final String TRANSFORMATION = "DES/ECB/PKCS5Padding";
private static final String KEY = "YOUR_KEY"; // 8个字符的密钥
public static void encrypt(File inputFile, File outputFile) throws Exception {
doCrypto(Cipher.ENCRYPT_MODE, inputFile, outputFile);
}
public static void decrypt(File inputFile, File outputFile) throws Exception {
doCrypto(Cipher.DECRYPT_MODE, inputFile, outputFile);
}
private static void doCrypto(int cipherMode, File inputFile, File outputFile) throws Exception {
try (FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(outputFile)) {
SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(cipherMode, secretKey);
byte[] inputBytes = new byte[(int) inputFile.length()];
inputStream.read(inputBytes);
byte[] outputBytes = cipher.doFinal(inputBytes);
outputStream.write(outputBytes);
}
}
public static void main(String[] args) {
File inputFile = new File("input.txt");
File encryptedFile = new File("encrypted.txt");
File decryptedFile = new File("decrypted.txt");
try {
encrypt(inputFile, encryptedFile);
decrypt(encryptedFile, decryptedFile);
System.out.println("File encryption and decryption completed.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
请注意,上述代码中的密钥`KEY`应该是8个字符的字符串。你可以根据需要修改密钥和文件名,并确保文件存在。加密后的文件将保存在`encrypted.txt`,解密后的文件将保存在`decrypted.txt`。
请记得在使用加密算法时,要妥善保管好密钥,以确保数据的安全性。
阅读全文