Using Facebook Conceal Library for Encryption

In this post i will show you how to use Facebook conceal library for encryption and decryption. You can read more about the conceal project here.

Conceal provides a set of Java APIs to perform cryptography on Android. It was designed to be able to encrypt large files on disk in a fast and memory efficient manner.

Overview of using Conceal

Encrypting concent

Encrypting content can be easily done with a few lines of code.

// Creates a new Crypto object with default implementations of 
// a key chain as well as native library.
Crypto crypto = new Crypto(
  new SharedPrefsBackedKeyChain(context),
  new SystemNativeCryptoLibrary());

// Check for whether the crypto functionality is available
// This might fail if android does not load libaries correctly.
if (!crypto.isAvailable()) {

OutputStream fileStream = new BufferedOutputStream(
  new FileOutputStream(file));

// Creates an output stream which encrypts the data as
// it is written to it and writes it out to the file.
OutputStream outputStream = crypto.getCipherOutputStream(

// Write plaintext to it.

The above code does the following:
– creates an instance of Crypto using the default implementation of SharedPrefsBackedKeyChain provided by conceal.
SharedPrefsBackedKeyChain stores the encryption keys in apps shared preferences.
– creates an instance of OutputStream which takes a output stream of a file.
– Creates an output stream which encrypts the data as it is written to it and writes it out to the file.

Note: The keys are install specific and will get cleared when the app in reinstalled. So you wont be able to decrypt already encrypted files on reinstallation of the app on the same device. Again you wont be able to decrypt the files on a different device as a new set of keys will be generated.

Decrypting content

The following code can be used to decrypt content.

// Get the file to which ciphertext has been written.
FileInputStream fileStream = new FileInputStream(file);

// Creates an input stream which decrypts the data as
// it is read from it.
InputStream inputStream = crypto.getCipherInputStream(

// Read into a byte array.
int read;
byte[] buffer = new byte[1024];

// You must read the entire stream to completion.
// The verification is done at the end of the stream.
// Thus not reading till the end of the stream will cause
// a security bug. 
while ((read = != -1) {
  out.write(buffer, 0, read);


Note: If the keys change or the file is written with some other text which can’t be decrypted then it throws an error that the files or the keys were tampered.

This content has been helpful to you?

Thanks for contributing!

Yes No