How to Hide API and Secret Keys in Android Studio? - GeeksforGeeks

15 May, 2021
API (Application Programming Interface) is a set of codes that helps in propagating information from one software or an application to the other. Tech companies create their software and APIs, which can be used to build new applications and features by their employees, making them private to use. However, some companies lease their APIs to third parties (can be other companies, developers, contributors) to implement features from their software in their projects, at some minimal cost and restricted use. So if you purchase or lease an API from a company, the company will provide you with an API key, which you must declare in your project to validate the API permission and access the features.
So it becomes crucial to hide API keys while using them to build applications as you have purchased or leased them. There are several ways of wrapping them within the application. We want to share with you an ethical way to secure your API key while building applications in Android Studio through this article. Refer to the flowchart below and try understanding the approach.
Approach
To hide a key, follow the steps below:
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Go to the .gitignore file in the projects in the menu
In the left top corner of the Android Studio IDE, you will find a menu where you can view the same project in different views. Click it and select the project option.
Select the Project option in the menu
In the project option, you will find the Gradle folder in which you need to open the .gitignore file.
Click on the .gitignore file to open it
Step 3: Check if local.properties is listed in the .gitignore file
In the .gitignore file, check if local.properties is listed. .gitignore will ignore every file listed in it during the build.
Step 4: Go to local.properties  file in the gradle folder and declare the API/Secret key
In the same gradle folder, you will find the local.properties file. Open it and declare the key as shown.
Step 5: Go to build.gradle  in the app > src folder and append the following Google plugin
Now go to the build.gradle file and add the below plugin in the plugins as shown.
plugins {
    id 'com.google.secrets_gradle_plugin' version '0.4'
}
After adding the plugin, click on the Sync Now option.
Step 6: Go to AndroidManifest.xml and create a meta-data
Now go to the AndroidManifest.xml file and declare a meta-data. Meta-data must be declared between the activity and application finishing tags.
XML
<application>        .        .        .        .                <activity>            .            .            .            .        </activity>      <meta-data        android:name = "keyValue"        android:value = "${KEY}"/>      </application>
Step 7: Go to MainActivity.kt  and type in the below code to get the KEY value from the meta-data in AndroidManifest.xml
Add the following code in the main program to call the key. To check if the key is fetched, we will generate a toast displaying the key value.
Kotlin
XML
package com.geeksforgeeks.hidingapikeysandroid  import android.content.pm.ApplicationInfoimport android.content.pm.PackageManagerimport android.os.Bundleimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity    class MainActivity : AppCompatActivity() {    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)          val ai: ApplicationInfo = applicationContext.packageManager            .getApplicationInfo(applicationContext.packageName, PackageManager.GET_META_DATA)        val value = ai.metaData["keyValue"]          val key = value.toString()        Toast.makeText(applicationContext,key,Toast.LENGTH_LONG).show()    }}
<!--There's nothing to change in the front-end--><?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout     xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity">      <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="GeeksforGeeks"        app:layout_constraintBottom_toBottomOf="parent"        app:layout_constraintLeft_toLeftOf="parent"        app:layout_constraintRight_toRightOf="parent"        app:layout_constraintTop_toTopOf="parent" />  </androidx.constraintlayout.widget.ConstraintLayout>
Output:
Screenshot when the program runs
We are able to see a Toast with the same key value. This means everything worked fine and we could successfully fetch the key. Now we can use the key validating the API and implement its features.
Android-Studio
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create and Add Data to SQLite Database in Android?
Broadcast Receiver in Android With Example
Resource Raw Folder in Android Studio
CardView in Android With Example
Services in Android with Example
Broadcast Receiver in Android With Example
Android UI Layouts
Services in Android with Example
Android RecyclerView in Kotlin
Content Providers in Android with Example