02nd September, 2017

XOR cipher in Java

A binary XOR stream cipher written in Java.

This is a small Java program that reads an input file byte-by-byte, XORs each byte by a key, and streams each byte to an output file.

This program works by streaming data from in input file one byte at a time through a function that XORs the bits against a byte from a key - each ciphered byte is then written to an output file before reading the next byte from the input file. The input file is never loaded directly into memory, so it is possible to cipher a very large file (if you really wanted to) without flooding your system's memory.

This jar requires three arguments at execution: the name of the file containing the key data, the name of the file containing the data you want to cipher against the key, and the name of the output file. Both input and key files are read as binary files, so it is possible to cipher anything against anything, for example: an mp3 file against a png file.

Example usage

  
java -jar xor-cipher.jar key.txt plain_text.txt cipher_text.txt
  

Source code

  
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.FileInputStream;
import java.io.FileOutputStream;


public class Main {

    public static void main(String[] args) {
        try {
            // load key into byte array
            byte[] key = Files.readAllBytes(Paths.get(args[0]));
            // open input and output files
            FileInputStream inputStream = new FileInputStream(args[1]);
            FileOutputStream outputStream = new FileOutputStream(args[2]);
            int currentByte;
            int counter = 0;
            // read input file byte by byte
            while ((currentByte = inputStream.read()) != -1) {
                // xor byte by current position in key byte array and write to output file
                outputStream.write(currentByte ^ key[counter % key.length]);
                counter++;
            }
            System.out.println(String.format("Wrote %s bytes", counter));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
  

Thank you for reading.

🍕🍕🍕


Leave a comment

Invalid or missing field(s).
Comment sent successfully, please wait for it to be approved.

This post has no comments