本文實例為大家分享了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();
}
}
}
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。