Monday, July 31, 2017

Starting with Basic File Cryptography (XOR Cipher)

  In this blog post, I'll discuss one interesting basic cipher technique to garble a file: The "XOR Cipher". What it does is obviously apply XOR (outputs true if both inputs are different) function for every bytes.

  It's not rocket-science like other more sophisticated algorithms like AES, DES, or Blowfish; but adequate for blazingly-fast-low-level-security encryption.

  The snippets I will show you adds a little twist. We will only encrypt the first 512 bytes of the file so that our code is scalable for larger files.


The code:

import java.io.*;
public class ImageCrypto {
private static final int XOR_KEY = 345;
private static final int BYTE_LENGTH = 512;
public static void applyXor( File file ) throws IOException {
RandomAccessFile rac = new RandomAccessFile(file, "rw");
byte[] data = new byte[BYTE_LENGTH];
rac.read( data );
byte[] newData = xor( data );
rac.seek(0);
rac.write(newData);
rac.close();
}
public static byte[] xor( byte[] data ) {
byte[] newData = new byte[data.length];
for (int i = 0; i < data.length; i++) {
newData[i] = xor(data[i]);
}
return newData;
}
public static byte xor(byte b) {
return (byte) (0xFF & ((int) b ^ XOR_KEY));
}
}

Some test:
public static void main(String[] args) throws IOException {
File file = new File( "D:\\test images\\8.png" );
long start = System.nanoTime();
ImageCrypto.applyXor(file);
long end = System.nanoTime() - start;
System.out.printf("Took: %d nanoseconds or %d milliseconds\n", end, (end/1000000));
}
Output:
Took: 1085333 nanoseconds or 1 milliseconds
view raw Main.java hosted with ❤ by GitHub

No comments:

Post a Comment

Starting with Basic File Cryptography (XOR Cipher)

  In this blog post, I'll discuss one interesting basic cipher technique to garble a file: The "XOR Cipher". What it does is o...