I want to encrypt image from the sd card and store it again in SD card again using AES. The main idea is the application browse an image, then encrypt it when I push a button, then store it in sd card. so my image would be secure.
I already succeed do string encryption using AES from this tutorial http://www.androidsnippets.com/encryptdecrypt-strings, but I don’t have idea how to do this with an image, not string.
This is how I do it with a string:
public static String encrypt(String seed, String cleartext) throws Exception
{
byte[] rawKey = getRawKey(seed.getBytes());
byte[] result = encrypt(rawKey, cleartext.getBytes());
return toHex(result);
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception
{
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
Can anyone help me give example code how to encrypt an image with AES?
maybe it must using I/O file stream but I don’t have an idea how to implement with this code.
If you take user input for the password make sure to read this answer.
You should take a look at:
CipherInputStream and CipherOutputStream. They are used to encrypt and decrypt byte streams.
I have a file named
cleartext. The file contains:Now, you have an
encrypt()function:After you execute this function, there should be a file names
encrypted. The file contains the encrypted characters.For decryption you have the
decryptfunction:After the execution of decrypt, there should be a file named
decrypted. This file contains the free text.You write you’re a “noob” but depending on the use-case of encryption you could do a lot of harm if you’re not doing it the right way. Know your tools!
Usage of CipherOutputStream Oracle documentation:
Thus, the encryption should work. When you reverse the process, you should be able to read the decrypted bytes.