How to encrypt and decrypt file in Android?

AndroidSecurityEncryption

Android Problem Overview


I want to encrypt file and store it in SD card. I want to decrypt that encrypted file and store it in SD card again. I have tried to encrypt file by opening it as file stream and encrypt it but it is not working. I want some idea on how to do this.

Android Solutions


Solution 1 - Android

Use a CipherOutputStream or CipherInputStream with a Cipher and your FileInputStream / FileOutputStream.

I would suggest something like Cipher.getInstance("AES/CBC/PKCS5Padding") for creating the Cipher class. CBC mode is secure and does not have the vulnerabilities of ECB mode for non-random plaintexts. It should be present in any generic cryptographic library, ensuring high compatibility.

Don't forget to use a Initialization Vector (IV) generated by a secure random generator if you want to encrypt multiple files with the same key. You can prefix the plain IV at the start of the ciphertext. It is always exactly one block (16 bytes) in size.

If you want to use a password, please make sure you do use a good key derivation mechanism (look up password based encryption or password based key derivation). PBKDF2 is the most commonly used Password Based Key Derivation scheme and it is present in most Java runtimes, including Android. Note that SHA-1 is a bit outdated hash function, but it should be fine in PBKDF2, and does currently present the most compatible option.

Always specify the character encoding when encoding/decoding strings, or you'll be in trouble when the platform encoding differs from the previous one. In other words, don't use String.getBytes() but use String.getBytes(StandardCharsets.UTF_8).

To make it more secure, please add cryptographic integrity and authenticity by adding a secure checksum (MAC or HMAC) over the ciphertext and IV, preferably using a different key. Without an authentication tag the ciphertext may be changed in such a way that the change cannot be detected.

Be warned that CipherInputStream may not report BadPaddingException, this includes BadPaddingException generated for authenticated ciphers such as GCM. This would make the streams incompatible and insecure for these kind of authenticated ciphers.

Solution 2 - Android

I had a similar problem and for encrypt/decrypt i came up with this solution:

public static byte[] generateKey(String password) throws Exception
{
	byte[] keyStart = password.getBytes("UTF-8");
	
	KeyGenerator kgen = KeyGenerator.getInstance("AES");
	SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
	sr.setSeed(keyStart);
	kgen.init(128, sr);
	SecretKey skey = kgen.generateKey();
	return skey.getEncoded();
}
	
public static byte[] encodeFile(byte[] key, byte[] fileData) throws Exception
{

    SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypted = cipher.doFinal(fileData);
    
    return encrypted;
}
	
public static byte[] decodeFile(byte[] key, byte[] fileData) throws Exception
{
    SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
       
    byte[] decrypted = cipher.doFinal(fileData);
        
    return decrypted;
}

To save a encrypted file to sd do:

File file = new File(Environment.getExternalStorageDirectory() + File.separator + "your_folder_on_sd", "file_name");
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
byte[] yourKey = generateKey("password");
byte[] filesBytes = encodeFile(yourKey, yourByteArrayContainigDataToEncrypt);
bos.write(fileBytes);
bos.flush();
bos.close();

To decode a file use:

byte[] yourKey = generateKey("password");
byte[] decodedData = decodeFile(yourKey, bytesOfYourFile);

For reading in a file to a byte Array there a different way out there. A Example: http://examples.javacodegeeks.com/core-java/io/fileinputstream/read-file-in-byte-array-with-fileinputstream/

Solution 3 - Android

You could use java-aes-crypto or Facebook's Conceal

java-aes-crypto

Quoting from the repo

> A simple Android class for encrypting & decrypting strings, aiming to > avoid the classic mistakes that most such classes suffer from.

Facebook's conceal

Quoting from the repo

> Conceal provides easy Android APIs for performing fast encryption and > authentication of data

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPratikView Question on Stackoverflow
Solution 1 - AndroidMaarten BodewesView Answer on Stackoverflow
Solution 2 - AndroidZeroTekView Answer on Stackoverflow
Solution 3 - Androiduser158View Answer on Stackoverflow