Encrypt only the content of an image file not enti

2019-02-16 01:00发布

问题:

I am creating an APP and need to encript only the content of an image. I need that the file was still an image after conversion, but the image showed does not show as the original.

For example, I will send the image encrypted to other user and this one will be able to show and image (but not the original), but the original image was encrypted in that file.

With the following algorythm I encrypted the entire file, and this cannot be opened as image due the header is encrypted as well.

I am using this algorythm but I do not know how to only encrypt data or how to add/modify the headers of an image in java/android:

public byte[] encrypt_image(Bitmap bm, String password_) {

    byte[] encryptedData = null;

    try{
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] b = baos.toByteArray();  

        byte[] keyStart = password_.getBytes();
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
        sr.setSeed(keyStart);
        kgen.init(128, sr); 
        SecretKey skey = kgen.generateKey();
        byte[] key = skey.getEncoded();    

        // Encrypt
        encryptedData = Security.encrypt(key,b);


    }catch (Exception e) {
        Log.e("encrpyt_image()", e.getMessage());
    }
    return encryptedData;
}

Anyone has an idea about how to codify that, I've been searching in internet with no success.

回答1:

I guess the get/setPixels methods may be the easiest way to do this.

int[] pixels = new int[bm.getWidth() * bm.getHeight()];
bm.getPixels(pixels, 0, bm.getWidth(), 0, 0, bm.getWidth(), bm.getHeight()); 
encryptIntArray(pixels);
bm.setPixels(pixels, 0, bm.getWidth(), 0, 0, bm.getWidth(), bm.getHeight());

Now you just have to write the encryptIntArray method.

edit: You could also try to use a ByteBuffer, then you don't have to do the conversion.

ByteBuffer bb = ByteBuffer.allocate(bm.getByteCount());
bm.copyPixelsToBuffer(bb);
byte[] b = bb.array();
bm.copyPixelsFromBuffer(ByteBuffer.wrap(Security.encrypt(key,b)));

I haven't tested that code though.