How to Secure API Key in Android Studio

Ahmad Sufyan
2 min readMay 8, 2022

--

API keys are very sensitive when you put them directly in program code. When you push to git then API key will also be easily visible to others so it can be misued. For that you need to hide or secure the API key when working with git so that it’s not easily seen by others.

Here are practical steps to secure your API keys:

  1. Go to your gradle.properties file and then put your API key as shown below.
kotlin.code.style=official
# Enables namespacing of each library's R class so that its R class includes only the
# resources declared in the library itself and none from the library's dependencies,
# thereby reducing the size of the R class for that library
android.nonTransitiveRClass
=true
API_KEY = "9aeb3df8-fb69-4625-8e3c-fcc42e103bb8"

2. After that open your build.gradle file and add buildConfigField in android block.

android {
compileSdk 32

defaultConfig {
applicationId "com.zerodev.secureapikey"
minSdk 21
targetSdk 32
versionCode 1
versionName "1.0"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

buildConfigField("String", "API_KEY", API_KEY)
}

......
......
}

3. Last, to hide it from git, add your gradle.properties to .gitignore file. Switch your android to project structure file and open .gitignore then put gradle.properties like this.

/build
/captures
.externalNativeBuild
.cxx
local.properties
/gradle.properties

Don’t forget to rebuild your project after doing that steps.

Now, you can access the API key with BuildConfig.API_KEY wherever you need it.

--

--

Ahmad Sufyan
Ahmad Sufyan

Written by Ahmad Sufyan

I love to learn something new especially about mobile development, currently working as a mobile engineer with flutter and kotlin

No responses yet