A strategy to secure your API keys using Gradle

Shhhhh!

Keep the API keys hidden is a constant concern specially when working on a shared or public repository. This article will show a very simple approach to solve this problem using Gradle.

Step #1: create a keystore.properties file.

This file will contains all the private keys. Create it on your project root and write down the API keys on property=value notation.

keystore.properties

Remember to use quotation marks when dealing with String values.

Step #2: Keep keystore.properties privately.

Make sure keystore.properties will not be under your version control system. If you are using Git and Android Studio, you can add it to .gitignore file.

Add to .gitignore file

Step #3-java: Make the property accessible programatically via Java.

Here is the magic: By configuring your build.gradle file you will be able to access the keystore.properties variable programatically in an easy way (static constants will be automatically created in BuildConfig).

To achieve that, first of all define a variable in your build.gradle module file and load the keystore.properties file.

def keystorePropertiesFile = rootProject.file("keystore.properties")
def keystoreProperties = new Properties()
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))

After that, configure the field that will generate static constants accessible via the auto generated BuildConfig class.

android{
(...)
    buildTypes.each {
it.buildConfigField 'String', 'OPEN_WEATHER_MAP_API_KEY', keystoreProperties['OpenWeatherMapApiKey']
    }
}

A correspondent static constant will be created and you can access it programatically:

String apiKey = BuildConfig.OPEN_WEATHER_MAP_API_KEY;

Step #3-AndroidManifest: Make the properties accessible on AndroidManifest file.

If you want to access the configured property from AndroidManifest, for example a Google Maps API key, you can write the manifest entry replacing the hardcode key by a variable. Like that:

<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="${GOOGLE_MAP_KEY}"/>

This variable must be created on build.gradle as a manifest placeholder.

buildTypes {
debug {
manifestPlaceholders = [ GOOGLE_MAP_KEY:keystoreProperties['GoogleMapKeyDebug']]
}
release {
manifestPlaceholders = [ GOOGLE_MAP_KEY:keystoreProperties['GoogleMapKeyRelease']]
}
}