Encrypting Assets File via Gradle Task (build variants + flavors support) for Android Projects
While building an Android app, sometimes we need to include an assets file which needs to be encrypted while packaging apk but decrypted while running the app. Encrypting this file manually might be an option.
The Problem
Now, lets consider following scenarios.
- We need to modify encrypted file as per requirements
- We need to know the contents of encrypted file without running the app
- Maintaining this file separately for each build flavor and variants
If done manually this can be a cumbersome task.
Solution — Writing a Gradle Task for Encrypting File
Setup
With the help of Gradle task we can automate file encryption. Let me explain following steps with the help of an example. Let us consider we have project named ‘gradle-file-encryption’ with following directory structure.
Now lets suppose this app has two product flavors(‘flavor1’ and ‘flavor2’) and two build variants (‘debug’ and ‘release’).
Next, we have a file named ‘config.txt’ which contains confidential data. This file data varies with product flavor and build variants. Before writing our gradle task, we will first keep original file in a separate folder (let say folder name ‘confidential-file’) in our project segregated by build flavors and variants as follows -
Now we will write gradle task to selectively pick up ‘config.txt’ as per selected build flavor and variant and packaging it directly into our apk.
Where’s The Code?
I will be using gradle-crypto library to encrypt file in gradle task and decrypt file in our application code.
To use this library in gradle we need to add it as a classpath dependency in buildscript
Also, define variables key, salt & output file name which will be used to encrypt/decrypt this file.
To make these variables accessible in android via BuildConfig.java, we need to declare them in app build.gradle inside android defaultConfig block
Now, we will define a method ‘encryptfile’ in our gradle file which will take build variant and build flavor as parameters and generates encrypted file accordingly.
Afterwards, declare tasks for build flavors and variants
We will now register these dynamically generated tasks to encrypt file when we build/run apk.
For accessing gradle-crypto library in android, add this as a dependency in app build.gradle
This file will now be accessible by our java code.
I’ve created a sample project on GitHub.