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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

百无1用是书生   2021-03-30 我要评论

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们