java uses XOR to encrypt and decrypt files

  • 2021-07-10 19:41:44
  • OfStack

This article example for everyone to share java using XOR file encryption and decryption of the specific code, for your reference, the specific content is as follows

1. How to encrypt files using XOR

One number is exclusive to another number twice, and the result is that 1 must be itself

2. Encrypt files using XOR


/**
 *  Encrypt the contents of a file 
 *  Use XOR to set the a.txt Encrypted copy out 1 A b.txt , put it in the same place 1 Folders under 
*/
 @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){
  // Exclude or on the read bytes 1 Number, encrypted output 
  out.write(data^1234);
  }
 }catch (Exception e){
  e.printStackTrace();
 }finally {
  // In finally Close the open stream in the 
  if (in!=null){
  try {
   in.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
  }
  if (out!=null){
  try {
   out.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
  }
 }
 }

3. Decrypt files using XOR


 /**
 *  Decrypt the contents of a file 
 *  Will use exclusive OR to encrypt the copied b.txt Decrypt to c.txt , put it in the same place 1 Folders under 
 */
 @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){
  // Exclude or on the read bytes 1 Number, encrypted output 
  out.write(data^1234);
  }
 }catch (Exception e){
  e.printStackTrace();
 }finally {
  // In finally Close the open stream in the 
  if (in!=null){
  try {
   in.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
  }
  if (out!=null){
  try {
   out.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
  }
 }
 }

Related articles: