Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify the bytes read by an InputStream while reading, not later

I need to make a simple sort of encryption so that the normal end user can't access some files easily.

The files that are read by an FileInputStream are html files, pngs, jpegs and different simple text files (javascript, xml, ...)

What I currently do is this:

public static byte[] toEncryptedByteArray(InputStream input) throws IOException {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    copy(input, output, true);
    return output.toByteArray();
}

public synchronized static final int copy(final InputStream input, final OutputStream output, final boolean modify) throws IOException {
    if (input == null || output == null) {
        throw new IOException("One stream is null!");
    }
    byte[] mBuffer = new byte[DEFAULT_BUFFER_SIZE];
    int count = 0;
    int n;
    while ((n = input.read(mBuffer)) != -1) {
        if (modify) {
            for ( int i = 0 ; i < n ; i++ ) {
                mBuffer[i] = (byte) ~mBuffer[i]; // byte manipulation
            }
        }
        output.write(mBuffer, 0, n);
        output.flush();
        count += n;
    }
    mBuffer = null;
    return count;
}

The memory footprint is huge as I have the complete byte array in my memory (we talk about bitmaps with >2mb in memory).

I thought I could simple extend the FileInputStream class and do the byte manipulation while reading the content of the file. That would reduce the memory usage as I could use Bitmap.decodeStream(inputstream) instead of creating a byte array to get the bitmap from... but here I am stuck totally. The read() and the readBytes(...) methods are native, so I can't override them.

Please spread the light in my darkness...

like image 777
WarrenFaith Avatar asked Nov 20 '25 00:11

WarrenFaith


1 Answers

Streams are designed to wrap. That's why you frequently see lines like:

InputStream is=new BufferedInputStream(new FileInputStream(file));

So, create a DecryptingInputStream that does your decryption, wrapping around another InputStream.

All that being said, this won't be tough to crack, as your decryption keys and algorithm will be easily determinable by anyone who decompiles your app.

like image 77
CommonsWare Avatar answered Nov 22 '25 15:11

CommonsWare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!