服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - java使用异或对文件进行加密解密

java使用异或对文件进行加密解密

2021-07-24 15:16百无1用是书生 Java教程

这篇文章主要为大家详细介绍了java使用异或方式对文件进行加密解密,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了java使用异或对文件进行加密解密的具体代码,供大家参考,具体内容如下

1.使用异或的方式加密文件的原理

一个数异或另一个数两次,结果一定是其本身

2.使用异或的原理加密文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
 * 将文件内容加密
 * 使用异或的方式将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.使用异或的原理解密文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* 将文件内容解密
* 将使用异或的方式加密复制出的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();
 }
 }
}
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/qq_37462735/article/details/77507987

延伸 · 阅读

精彩推荐