利用異或運算加密文件


主要利用了異或運算的如下特性:

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();
        }

    }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM