当前位置: 移动技术网 > IT编程>开发语言>Java > java使用异或对文件进行加密解密

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

2019年07月19日  | 移动技术网IT编程  | 我要评论

康洪涛博客,男足世界排名,嫚裳

本文实例为大家分享了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();
  }
  }
 }
 }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网