java中使用異或的方式對文件進行加密解密

1.使用異或的方式加密文件的原理

一個數異或另一個數兩次,結果一定是其本身

2.使用異或的原理加密文件

    /**
     * 將文件內容加密
     * 使用異或的方式將a.txt加密複製出一個b.txt,放到同一個文件夾下
     */
    @Test
    public void encryptFile(){
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            String sourceFileUrl = "C:\\Users\\admin\\Desktop\\testIO\\a.txt";
            String targetFileUrl = "C:\\Users\\admin\\Desktop\\testIO\\b.txt";
            in = new FileInputStream(sourceFileUrl);
            out = new FileOutputStream(targetFileUrl);
            int data = 0;
            while ((data=in.read())!=-1){
                //將讀取到的字節異或上一個數,加密輸出
                out.write(data^1234);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //在finally中關閉開啓的流
            if (in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out!=null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

3.使用異或的原理解密文件

    /**
     * 將文件內容解密
     * 將使用異或的方式加密複製出的b.txt解密到c.txt,放到同一個文件夾下
     */
    @Test
    public void decryptFile(){
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            String sourceFileUrl = "C:\\Users\\admin\\Desktop\\testIO\\b.txt";
            String targetFileUrl = "C:\\Users\\admin\\Desktop\\testIO\\c.txt";
            in = new FileInputStream(sourceFileUrl);
            out = new FileOutputStream(targetFileUrl);
            int data = 0;
            while ((data=in.read())!=-1){
                //將讀取到的字節異或上一個數,加密輸出
                out.write(data^1234);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //在finally中關閉開啓的流
            if (in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out!=null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }









發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章