If you want to save / load encoded images then
- you must use a lossless image compression algorithm e.g. png, gif
- you would also need to store the random seed value so you can decode it.
I suggest that you avoid using random numbers for the reason kfrajer stated. I would suggest the following approach
- Use the SHA-1 hashing algorithm to convert a password or passphrase to a 20 byte array (h[])
- convert the 20 byte array into an array of 17 integers (e[]) using bitwise operators to fill the 32 bits of an integer
e[0] = (h[0] << 24) | (h[1] << 16) | (h[2] << 8) | h(3)
e[1] = (h[1] << 24) | (h[2] << 16) | (h[3] << 8) | h(4)
...
e[16] = (h[16] << 24) | (h[17] << 16) | (h[18] << 8) | h(19)
Then load the image pixels and loop through the array, xoring the image data with the next element in the integer array
img.loadPixels();
int[] d = img.pixels;
int ip = 0;
for(int i = 0; i < d.length; i++){
d[i] = d[i] ^ e[ip]; // perform XOR
ip = (ip + 1) % e.length; // loop through encryption values
}
img.updatePixels();
The advantage is that the SHA-1 algorithm has a standard implementation where random number generators can vary between machines.
Decoding the image can use the same code because the xor operation is reversable i.e.
if P = Q ^ N
is true then Q = P ^ N
is also true.
The Staganos library uses this approach when encrypting images although the algorithm is more complex because it uses a second hash algorithm (SHA-256) with the passphrase to generate an array used to rotate the color bits in the encrypted image. All the code for this is in the Encryption.java class.