Hi. I'm using bouncy castle to encrypt/decrypt binary data like images. I'm having a problem that is a bit hard to explain, so please bear with me.
Through testing I've noticed the following:
1. If I encrypt 1 byte the resulting cipher text is 8 bytes. If I encrypt 1024 bytes, the cipher text is 1032 bytes.
2. To avoid opening the entire file into memory I have to encrypt/decrypt sections at a time.
3. The section I encrypt has the be the EXACT section I decrypt.
The implications of this is that if I have a photo that is 1000 bytes, I have to encrypt 500 bytes and 500 bytes which turns into two cipher text blocks of 508 bytes and 508 bytes. When decrypting this file I have to read in two 508 byte cipher blocks which turns into a 1000 byte image again.
Now, the problem is that when I decrypt a file I have to know the size of each cipher text block in the file so I don't try to decrypt half of one block and half of another thinking it's a single block. Clearly this is a HUGE hurdle. I'm hoping someone knows something I don't know, like perhaps some special character sequence that indicates the end of a cipher block.
My current solution is painfully slow -- I am using the least common denominator and encrypting my files 1 byte at a time, so when I decrypt them I know that each and every cipher text block is 8 bytes in length per the code sample below. If I try to take 1024 bytes at a time the blocks are unpredictable sizes -- especially the last one where it takes whatever is left.
byte[] b = new byte[1];
for (int n; (n = is.read(b)) != -1;){
byte[] c = Cryptor.getInstance().encrypt(b);
os.write(c);
}
Any suggestions are appreciated.