利用异或运算加密文件
主要利用了异或运算的如下特性:
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(); } }