JAVA加密文件内容(异或^方式)
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>***</version>
</dependency>
package pub;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Console;
import java.io.File;
import java.io.RandomAccessFile;
import java.util.List;
import java.util.Scanner;
public class AppMain {
public static final long MINIMUM_FILE_SIZE = 10240L;
public static final int KEY = ******;
public static String DEC_MARK = "DEC0000000000000";
public static String ENC_MARK = "ENC1111111111111";
public static void encFile(File file, int key) {
long start = System.currentTimeMillis();
try (RandomAccessFile raf = new RandomAccessFile(file, "rw")) {
raf.seek(raf.length() - 16);
byte[] endBytes = new byte[16];
raf.read(endBytes, 0, endBytes.length);
String mark;
int markIndex = 2;
if (ENC_MARK.equals(new String(endBytes))) {
markIndex = 1;
mark = DEC_MARK;
Console.log("文件=[{}]为加密状态,现操作解密:", file);
} else if (DEC_MARK.equals(new String(endBytes))) {
markIndex = 0;
Console.log("文件=[{}]为解密状态,现操作加密:", file);
mark = ENC_MARK;
} else {
mark = ENC_MARK;
Console.log("文件=[{}]为初始状态,现操作加密:", file);
}
raf.seek(0);
for (int i = 0; i < raf.length() / MINIMUM_FILE_SIZE; i++) {
byte[] bytes = new byte[1024];
raf.seek(MINIMUM_FILE_SIZE * i);
raf.read(bytes, 0, bytes.length);
byte[] newBytes = new byte[1024];
for (int j = 0; j < bytes.length; j++) {
newBytes[j] = (byte) (bytes[j] ^ key);
}
raf.seek(MINIMUM_FILE_SIZE * i);
raf.write(newBytes, 0, newBytes.length);
}
if (markIndex == 2) {
raf.seek(raf.length());
} else {
raf.seek(raf.length() - 16);
}
byte[] tempBytes = mark.getBytes();
raf.write(tempBytes, 0, tempBytes.length);
raf.close();
long end = System.currentTimeMillis();
Console.log("文件=[{}]=>{}成功,耗时=[{}]ms", file, markIndex == 1 ? "解密" : "加密", (end - start));
} catch (Exception e) {
Console.error("文件=[{}]加/解密失败,错误原因:[{}]", file, e.getMessage());
e.printStackTrace();
}
}
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("请输入密码:");
String keyStr = scanner.nextLine();
if (!String.valueOf(KEY).equals(keyStr)) {
Console.error("密钥不正确,退出!\n");
return;
}
System.out.println("请输入加/解密文件夹路径:");
String encPath = scanner.nextLine();
if (!FileUtil.isDirectory(encPath)) {
Console.error("输入的文件夹路径=[{}]不正确,退出!");
return;
}
List<File> files = FileUtil.loopFiles(encPath, pathname -> !pathname.getName().toLowerCase().endsWith(".jar"));
for (File file : files) {
if (!file.exists() || file.isDirectory()) {
Console.error("文件=[{}]无法访问,无法加密,continue.", file);
continue;
}
if (file.length() < MINIMUM_FILE_SIZE) {
Console.error("文件=[{}] length=[{}]<[{}] 无法加密,continue.", file, file.length(), MINIMUM_FILE_SIZE);
continue;
}
if (!file.canWrite()) {
Console.error("文件=[{}]不可写,无法加密,continue.", file, MINIMUM_FILE_SIZE);
continue;
}
encFile(file, KEY);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}