欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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

时间:2021-04-14 09:06:35|栏目:JAVA代码|点击:

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

上一篇:Java中的泛型详解

栏    目:JAVA代码

下一篇:解决SpringBoot在后台接收前台传递对象方式的问题

本文标题:java使用异或对文件进行加密解密

本文地址:http://www.codeinn.net/misctech/101322.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有