How to secure/protect API keys in android application?

Published June 28, 2022

In every android application there we might use some api keys inside application. We will add them inside code and will publish the app into PlayStore by generate signed apk from Android studio. There will be an option to decompile apk ( Apk to Java Code)  and get the source code of the application and users can find respected API keys which are used in application. So how we will provide security for the api keys which are used inside android application. In this android example we will show you how to protect/secure api keys in application.
 

Let's get Started

secure api keys in android application

Create an Android project using Android studio
After project creation we will see one file called local.properties file in the folder structure.

In this file we will add our api keys..

Let say we have an api key as "12345678"

Now add this key inside local.properties file

How to access this key value inside our classes

For to use this api key we need to create a variable in build. gradle file and we use that variable where ever we wants

Inside build.gradle file we will read the data from local.properties file by three steps

 

Step 1: Load data from file by using below code
 

 Properties properties=new Properties()
properties.load(project.rootProject.file("local.properties").newDataInputStream())

 

Step 2: Define variable inside gradle file and assign our api key value to this variable by below code

buildConfigField "String","API_KEY","${properties.getProperty("API_Key")}"

 

to create any number of variables in gradle file using "buildConfigField" property

This will take 3 params type of the variable, name of the variable and value to assign variable

In the above code we have takes api key as String type and variable name as "API_KEY" and value is read from local.properties file

 

Step 3: Use this variable inside our classes/activities..

use variable as

BuildConfig.API_KEY

 We defined variables inside build file so before step3 we need to build application, then only we can access our variables

Sample code for Secure API KEYs in android application

local.properties file

sdk.dir=C\:\\Users\\USER\\AppData\\Local\\Android\\Sdk
API_Key="12345678"

 


build. gradle file code

 plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
}

android {
    namespace 'com.example.eec7_composeactivity'
    compileSdk 32

    defaultConfig {
        applicationId "com.example.eec7_composeactivity"
        minSdk 24
        targetSdk 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary true
        }

        Properties properties=new Properties()
        properties.load(project.rootProject.file("local.properties").newDataInputStream())

        buildConfigField "String","API_KEY","${properties.getProperty("API_Key")}"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
    buildFeatures {
        compose true
    }
    composeOptions {
        kotlinCompilerExtensionVersion '1.2.0-beta01'
    }
    packagingOptions {
        resources {
            excludes += '/META-INF/{AL2.0,LGPL2.1}'
        }
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'
    implementation 'androidx.activity:activity-compose:1.3.1'
    implementation "androidx.compose.ui:ui:$compose_version"
    implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
    implementation 'androidx.compose.material3:material3:1.0.0-alpha11'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
    debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"
    debugImplementation "androidx.compose.ui:ui-test-manifest:$compose_version"
}


   
   

MainActivity code
 

import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.TextUnitType
import androidx.compose.ui.unit.sp
import com.example.eec7_composeactivity.ui.theme.EEC7ComposeActivityTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            EEC7ComposeActivityTheme {
                // A surface container using the 'background' color from the theme

                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background,
                ) {
                    Greeting("Your API Key from Local.Properties file")
                }
            }
        }
    }
}

@Composable
fun Greeting(name: String) {
    Column (verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally){
        Text(text = "Secure API Keys in Android application" );
        Text(text = "\n")
        Text(text = "Hello $name! ${BuildConfig.API_KEY}")

    }
}

 

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    EEC7ComposeActivityTheme {
        Greeting("Android")
    }
}

 

Conclusion: In this Android example we covered how to secure/protect your API KEYs in android application using buildconfig variables.

 

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

201 Views