java使用異或對文件進行加密解密
更新時間:2019年03月22日 09:47:16 作者:百無1用是書生
這篇文章主要為大家詳細介紹了java使用異或方式對文件進行加密解密,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了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){ //將讀取到的字節(jié)異或上一個數,加密輸出 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){ //將讀取到的字節(jié)異或上一個數,加密輸出 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(); } } } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。