這個檔案加密方法是採用異或方式對文中每個位元組進行異或加密,邏輯非常簡單:
檔案加密代碼實現:
</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();}}