The File Encryption Tool

We are going to build a command-line tool that XOR-encrypts any file using a passphrase. Running this program twice will result in decrypted file and so on



import static java.lang.IO.println;
void main(String[] args) {

    // User executes this code with 3 arguments
    // src - source file which we want to decrypt
    // dest - destination file where we want create encrypted file
    // passphrase - key which will be used to encrypt and decrypt this file
    final String src = args[0].trim();
    final String dest = args[1].trim();
    final String passphrase = args[2].trim();

    try (var io = new BufferedInputStream(
            new FileInputStream(
                    src
            )
    ); var os = new BufferedOutputStream(
            new FileOutputStream(
                    dest
            )
    )) {
        long startTime = System.currentTimeMillis();
        long bytesProcessed = 0;
        int charIndex = 0;
        int b;
        while ((b = io.read()) != -1) {
            if (charIndex == passphrase.length()) charIndex = 0;
            bytesProcessed += b;
            b ^= passphrase.charAt(charIndex++);
            os.write(b);
            os.flush();
        }
        println("Time taken: " + (System.currentTimeMillis() - startTime) + "ms");
        println("Bytes processed " + bytesProcessed + "bytes");
    } catch (IOException e) {
        println(e.getMessage());
        throw new RuntimeException(e);
    }
}


java Main.java src dest passphrase

With this simple code we have encryption tool that encrypts any type of file.

Modern java is very powerful.