Reputation: 85
I am trying to encrypt an image in Android. I converted an image into a byte array. Later, I want to use the cipher text to create a brand new bitmap and save it. The code below is for my encryption
private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
private static int KEY_LENGTH = 256;
...
public static byte[][] encrypt(byte[] plaintext, SecretKey key, byte[] salt) {
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
byte[] iv = generateIv(cipher.getBlockSize());
IvParameterSpec ivParams = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, key, ivParams);
byte[] cipherText = cipher.doFinal(plaintext);
return new byte[][]{salt, iv, cipherText};
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}
The problem is that cipherText has extra 16 bytes when the function returns.
For example, the plaintext is of size 7680000 bytes, but cipherText has 7680016 bytes. The image is 1600x1200, so 1600x1200x4= 7680000. I cannot save 7680016 bytes as an image :( What are these extra 16 bytes? Am I doing something wrong?
Upvotes: 1
Views: 1817
Reputation: 6198
The extra 16 bytes are almost certainly due to padding. Padding makes the encryption somewhat more secure, but if you don't mind getting rid of that, you can change the third component of the cipher name ((which represents the padding algorithm) to NoPadding
, to give a cipher name of "AES/CBC/NoPadding"
.
You can find all the gory details about how cryptographic algorithm names work in the Java security architecture docs.
In general, however, you shouldn't really rely on the size of the output generated by a cipher -- the ciphers are carefully designed to be as secure as possible, and you should leave the output size up to them.
Upvotes: 2
Reputation: 697
I think you should not worry about the size of the file. When I have done similar task I had a 10 bytes extra in one particular bitmap image.
But, if you want to open the encrypted image to be openable, then you must alter the first 54 bytes of the bitmap file with the original image. (the header 54 bytes of the bmp gives the bitmap information)
sample:
I have encrypted this image file using openssl tool. Here how I selected first 54 bytes and replaced with the encrypted bitmap file.
If you wish to do something like this. Make sure that after decryption, you must also alter the 54 bytes from original header.
Upvotes: 1