Safe Storage of an API Key in Android Studio

RoryKelly
1 min readFeb 21, 2017

--

Lets imagine you’re building a nice app, one that connects to a third party service. Most APIs worth implementing feature an API key as a part of basic security. Checking this into source control isn’t the best idea. If you ever opensource your project (or parts of it) you can expose your key to any opportunistic github user.

One way to avoid this is to add the key to your gradle.properties file, then add this file to your git ignore (like anyone is using any other VCS system…I hear you shouting mecurial at me…If you’re shouting SVN….please stop). Magic, gradle.properties looks like this:

bighugelabs.key=“your key"

My build.gradle looks like this:

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
buildConfigField "String", "BIGHUGHE_LABS_KEY", project.property("bighugelabs.key")
}
debug {
buildConfigField "String", "BIGHUGHE_LABS_KEY", project.property("bighugelabs.key")
}
}

Then in java I reference my key like this:

private static String API_KEY = BuildConfig.BIGHUGHE_LABS_KEY;

Now you can have a public repository that can reference API keys Or have different keys for debug and release! If there is a better way comment, mail or tweet me!

--

--