java实现对文本文件进行加密和解密操作
时间: 2023-12-22 20:05:23 浏览: 111
Java中对文本文件进行加密和解密的操作可以使用加密算法和解密算法来实现。常用的加密算法有DES、AES、RSA等,解密算法则是对应的解密算法。下面是一个简单的示例,使用DES算法对文本文件进行加密和解密。
加密操作:
```java
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.SecureRandom;
public class FileEncryptor {
public static void encrypt(String key, File inputFile, File outputFile) throws Exception {
FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
SecureRandom secureRandom = new SecureRandom(key.getBytes());
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, secureRandom);
int length;
while ((length = inputStream.read(buffer)) != -1) {
byte[] output = cipher.update(buffer, 0, length);
if (output != null) {
outputStream.write(output);
}
}
byte[] output = cipher.doFinal();
if (output != null) {
outputStream.write(output);
}
inputStream.close();
outputStream.flush();
outputStream.close();
}
}
```
解密操作:
```java
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.SecureRandom;
public class FileDecryptor {
public static void decrypt(String key, File inputFile, File outputFile) throws Exception {
FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
SecureRandom secureRandom = new SecureRandom(key.getBytes());
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, secretKey, secureRandom);
int length;
while ((length = inputStream.read(buffer)) != -1) {
byte[] output = cipher.update(buffer, 0, length);
if (output != null) {
outputStream.write(output);
}
}
byte[] output = cipher.doFinal();
if (output != null) {
outputStream.write(output);
}
inputStream.close();
outputStream.flush();
outputStream.close();
}
}
```
示例中使用的是DES算法,可以根据需要替换为其他算法。对于密钥,建议使用安全的方式存储,例如通过密码学哈希函数对其进行散列,以保证安全性。
阅读全文