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
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() |
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 |
build. gradle file code
plugins { android { defaultConfig { testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" Properties properties=new Properties() buildConfigField "String","API_KEY","${properties.getProperty("API_Key")}" buildTypes { dependencies { implementation 'androidx.core:core-ktx:1.7.0' |
MainActivity code
import android.os.Build class MainActivity : ComponentActivity() { Surface( @Composable }
@Preview(showBackground = true) |
Conclusion: In this Android example we covered how to secure/protect your API KEYs in android application using buildconfig variables.
Article Contributed By :
|
|
|
|
243 Views |