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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |