RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
java使用异或对文件进行加密解密

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

专注于为中小企业提供网站制作、成都做网站服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业横峰免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了上1000家企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。

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();
  }
  }
 }
 }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。


当前文章:java使用异或对文件进行加密解密
文章网址:http://sczitong.cn/article/pdpses.html