簡單檔案加密/解密

來源:互聯網
上載者:User

這個檔案加密方法是採用異或方式對文中每個位元組進行異或加密,邏輯非常簡單:



檔案加密代碼實現:

</pre><pre name="code" class="java">package ********//<span style="color:#33cc00;">自己定義</span>;import java.io.File;import java.io.RandomAccessFile;import java.util.Scanner;public class Test1 {public static void main(String[] args) {System.out.println("輸入檔案路徑:");String  s = new Scanner(System.in).nextLine();File f =new File(s);if(!f.isFile()){System.out.println("請輸入正確的檔案路徑");return ;}System.out.println("KEY:");int key =new Scanner(System.in).nextInt();try {encrypt(f,key);System.out.println("加密/解密完成");} catch (Exception e) {System.out.println("加密/解密失敗");e.printStackTrace();}}private static void encrypt(File f, int key) throws Exception{/* * 1.建立RandomAccessFile 對象賦給raf * 2.單位元組迴圈讀取,讀取的位元組值賦給b * 3.b異或key,結果在賦給b * 4.定位下標回到前一位置seek(raf.getFilePointer()-1) * 5.將位元組值b 寫回到的檔案 * 6.關閉raf
<span style="white-space:pre"></span> * 採用單位元組訪問比較慢,這裡採用位元組數組形式 */RandomAccessFile raf =new RandomAccessFile(f, "rw");//單位元組訪問/*int b ;while((b=raf.read())!=-1){b=b^key;raf.seek(raf.getFilePointer()-1);;raf.write(b);}*///位元組數組訪問//1024 2048 4096 8192byte[] buff =new byte[8192];int n;//儲存每一批的數量while((n=raf.read(buff))!=-1){for(int i=0;i<n;i++){buff[i] ^= key;}raf.seek(raf.getFilePointer()-n);raf.write(buff, 0, n);}raf.close();}}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.