How to decode (shifting and xoring) a massive byte array in a fast way?
I need it for a file viewer application that opens the archive file and decodes the files inside and display them to the user. The files are encrypted with a byte shifting and xoring system. It is impossible for me to change the algorithm. Currently, I just read all the bytes and then run the Decode function on them.
The decode function that I currently use:
byte[] DecodeVOQ(byte[] EncodedBytes)
{
for (int i = 0; i < EncodedBytes.Length; i++)
{
EncodedBytes[i] ^= (byte)194;
EncodedBytes[i] = (byte)((EncodedBytes[i] << 4) | (EncodedBytes[i] >> 4));
}
return EncodedBytes;
}
Edit: I found out that the real performance problem is with displaying the text. Reading + Decoding is pretty fast.
One possible optimization would be to precompute the output for any input byte. So you’d have:
It’s quite possible that that will be slower than your existing bitshifting algorithm though. EDIT: I’ve just tried comparing this with the original bitshift but using a temporary local variable: they’re about the same.
Have you benchmarked the current performance? Is it definitely too slow? In particular, loading the file from just about any storage medium will be much much slower than the cost of decoding. I’ve just tried this on my laptop – for 200MB of data, it takes about half a second. (EDIT: With Marcelo’s answer, it takes under half a second.) Is that really too slow?
Would you be happy to use more than one processor? It’s an embarrassingly parallelizable routine, after all. If you’re using .NET 4, the TPL may well make this pretty simple.
I should emphasize again though that this isn’t “encryption” – it’s a mild form of obfuscation, in the same way that the base-64 encoding of a username/password for basic HTTP authentication is.