java使用異或?qū)ξ募M行加密解密
更新時間:2019年03月22日 09:47:16 作者:百無1用是書生
這篇文章主要為大家詳細介紹了java使用異或方式對文件進行加密解密,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了java使用異或?qū)ξ募M行加密解密的具體代碼,供大家參考,具體內(nèi)容如下
1.使用異或的方式加密文件的原理
一個數(shù)異或另一個數(shù)兩次,結(jié)果一定是其本身
2.使用異或的原理加密文件
/**
* 將文件內(nèi)容加密
* 使用異或的方式將a.txt加密復(fù)制出一個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é)異或上一個數(shù),加密輸出
out.write(data^1234);
}
}catch (Exception e){
e.printStackTrace();
}finally {
//在finally中關(guān)閉開啟的流
if (in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out!=null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3.使用異或的原理解密文件
/**
* 將文件內(nèi)容解密
* 將使用異或的方式加密復(fù)制出的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é)異或上一個數(shù),加密輸出
out.write(data^1234);
}
}catch (Exception e){
e.printStackTrace();
}finally {
//在finally中關(guān)閉開啟的流
if (in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out!=null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot多線程與任務(wù)調(diào)度總結(jié)
多線程與任務(wù)調(diào)度是java開發(fā)中必須掌握的技能,本文主要介紹了SpringBoot多線程與任務(wù)調(diào)度總結(jié),具有一定的參考價值,感興趣的可以了解一下2023-12-12
解決zuulGateway網(wǎng)關(guān)添加路由異常熔斷問題
這篇文章主要介紹了解決zuulGateway網(wǎng)關(guān)添加路由異常熔斷問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10
Java實現(xiàn)將String轉(zhuǎn)化為Int
這篇文章主要介紹了Java實現(xiàn)將String轉(zhuǎn)化為Int方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05
Springboot打包為Docker鏡像并部署的實現(xiàn)
這篇文章主要介紹了Springboot打包為Docker鏡像并部署的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12

