Anything in an application that the developer does not want exposed to users, hackers or the version control system is known as a Secret. The following is some of the information that you need to keep as a secret in your application:

  1. API Keys
  2. Authorization tokens
  3. Database Credentials
  4. Encryption Keys
  5. Passwords
  6. SSH keys
  7. Certificates
  8. OAuth Tokens

In this article, we are going to see how to hide these secrets in your application in Android Studio.

In the root directory of your project, you should have the local.properties file.

None

The next step is to add your API key to this file:

None

To ensure the local.properties file is ignored by the version control system that you are using you need to make sure it is in the .gitignore file.

None

The next step is to add the secret gradle plugin to your project. In your app-level build.gradle.kts file, add the plugin under plugins:

id("com.google.secrets_gradle_plugin") version "0.4"
None

After adding the plugin, now you can go to the AndroidManifest.xml file and add a meta-data tag. A meta-data tag needs to be just before the closing of your application tag. This binds your secret key to a manifest variable that can be accessed within your app.

 <meta-data
      android:name = "keyValue"
      android:value = "${KEY}"/>
None

Here's how you can access the API key from within your app either in a composable or an activity:

val context = LocalContext.current
val ai = context.packageManager
    .getApplicationInfo(context.packageName, PackageManager.GET_META_DATA)
val value = ai.metaData["keyValue"]
val key = value?.toString() ?: "No key found"
Toast.makeText(context, key, Toast.LENGTH_LONG).show()

By doing this, you will ensure that you have kept sensitive data from your version control system and maintain security in your android app.

Happy Coding!

For further reading:

  1. How to Hide Your API Keys in an Android Application
  2. How to Hide API and Secret Keys in Android Studio