java用异或加密解密文件
时间: 2024-06-13 07:06:41 浏览: 136
用”异或”加密解密-c语言程序设计与游戏开发
以下是Java使用异或方式对文件进行加密解密的示例代码:
加密:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class XorEncryptor {
public static void encrypt(File inputFile, File outputFile, String key) throws IOException {
FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(outputFile); byte[] buffer = new byte[1024];
int len;
int index = 0;
while ((len = inputStream.read(buffer)) != -1) {
for (int i = 0; i < len; i++) {
buffer[i] ^= key.charAt(index % key.length());
index++;
}
outputStream.write(buffer, 0, len);
}
inputStream.close();
outputStream.close();
}
}
```
解密:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class XorDecryptor {
public static void decrypt(File inputFile, File outputFile, String key) throws IOException {
FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int len;
int index = 0;
while ((len = inputStream.read(buffer)) != -1) {
for (int i = 0; i < len; i++) {
buffer[i] ^= key.charAt(index % key.length());
index++;
}
outputStream.write(buffer, 0, len);
}
inputStream.close();
outputStream.close();
}
}
```
其中,encrypt方法用于加密文件,decrypt方法用于解密文件。key为加密解密的密钥。
阅读全文