Skip to content

Instantly share code, notes, and snippets.

@pphilipp
Created April 17, 2017 09:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pphilipp/7d300326e535b78757e7fb4ef0e5166f to your computer and use it in GitHub Desktop.
Save pphilipp/7d300326e535b78757e7fb4ef0e5166f to your computer and use it in GitHub Desktop.
gradleConfig.md

A strategy to secure your API keys using Gradle

There is short approach for ensure secure storing of api keys and signIng apk data.

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.

Remember to use quotation marks when dealing with String values.

Keep keystore.properties privately

Add keystore.properties file to .gitignore file.

Make the property accessible programatically via Java

Configuring your build.gradle(app) file for getting access to keystore.properties

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;

Make properties accessible on Manifest.xml

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

Create variable on build.gradle

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

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

Copiright from Cássio Oliveira.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment