主要利用了異或運算的如下特性:
a ^ b ^ b = a ^ (b ^ b) = a ^ 0 = a;
b ^ b,由於每個位都是相同的,所以 b ^ b = 0;
而和 0 異或,值不變,因此 a ^ 0 = a。
也就是說可以將一個文件的每一字節都和一個數異或一次,則可以加密文件;再異或一次,則可以解密文件。
public static void encryptFile(String file){
byte[] buffer = new byte[1024];
try (FileInputStream fin = new FileInputStream(file);
FileOutputStream fout = new FileOutputStream(file + ".e")) {
int x = 0;
while (fin.available() > 0) {
int n = fin.read(buffer);
for (int i = 0; i < n; i++) {
buffer[i] ^= (x = (x + 1) % 9997); //異或加密
}
fout.write(buffer, 0, n);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
Files.delete(Paths.get(file));
Files.move(Paths.get(file + ".e"), Paths.get(file));
} catch (Exception e) {
e.printStackTrace();
}
}
