用java实现对文本文件进行加密和解密操作
时间: 2023-12-22 22:05:41 浏览: 122
Java文本文件加密与解密
可以使用Java的加密解密API来对文本文件进行加密和解密操作。下面是一个简单的示例代码:
```java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
public class FileEncryptionDecryption {
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
private static final String KEY_FILE = "key.txt";
public static void encrypt(String inputFile, String outputFile) throws Exception {
Key secretKey = getSecretKey();
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
try (BufferedReader reader = new BufferedReader(new FileReader(inputFile))) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
String line;
while ((line = reader.readLine()) != null) {
byte[] encrypted = cipher.doFinal(line.getBytes());
writer.write(Base64.getEncoder().encodeToString(encrypted));
writer.newLine();
}
}
}
}
public static void decrypt(String inputFile, String outputFile) throws Exception {
Key secretKey = getSecretKey();
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
try (BufferedReader reader = new BufferedReader(new FileReader(inputFile))) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
String line;
while ((line = reader.readLine()) != null) {
byte[] encrypted = Base64.getDecoder().decode(line);
byte[] decrypted = cipher.doFinal(encrypted);
writer.write(new String(decrypted));
writer.newLine();
}
}
}
}
private static Key getSecretKey() throws Exception {
Key secretKey;
if (new File(KEY_FILE).exists()) {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(KEY_FILE))) {
secretKey = (Key) ois.readObject();
}
} else {
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
keyGenerator.init(128);
secretKey = keyGenerator.generateKey();
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(KEY_FILE))) {
oos.writeObject(secretKey);
}
}
return secretKey;
}
}
```
在上面的示例代码中,我们使用了AES算法来进行加密和解密操作。我们还使用了Base64来对加密后的文本进行编码,以便于在文件中进行存储和读取。
你可以通过调用 `encrypt` 方法来加密一个文本文件,调用 `decrypt` 方法来解密一个加密后的文本文件。
下面是一个使用示例:
```java
public static void main(String[] args) throws Exception {
FileEncryptionDecryption.encrypt("original.txt", "encrypted.txt");
FileEncryptionDecryption.decrypt("encrypted.txt", "decrypted.txt");
}
```
在上面的示例中,我们将 `original.txt` 文件加密并保存到 `encrypted.txt` 文件中,然后将加密后的文本文件解密并保存到 `decrypted.txt` 文件中。
阅读全文