Storing Secret Keys in Android (2024)

Overview

Often your app will have secret credentials or API keys that you need to have in your app to function but you'd rather not have easily extracted from your app.

If you are using dynamically generated secrets, the most effective way to store this information is to use the Android Keystore API. You should not store them in shared preferences without encrypting this data first because they can be extracted when performing a backup of your data.

The alternative is to disable backups by setting android:allowBackup in your AndroidManifest.xml file:

<application ... android:allowBackup="true"></application>

You can also specify which files to avoid backups too by reviewing this doc.

Storing Fixed Keys

For storing fixed API keys, the following common strategies exist for storing secrets in your source code:

  • Hidden in BuildConfigs
  • Embedded in resource file
  • Obfuscating with Proguard
  • Disguised or Encrypted Strings
  • Hidden in native libraries with NDK
  • Hidden as constants in source code

The simplest approach for storing secrets in to keep them as resource files that are simply not checked into source control. The approaches below two ways of accomplishing the same goal.

Hidden in BuildConfigs

First, create a file apikey.properties in your root directory with the values for different secret keys:

CONSUMER_KEY="XXXXXXXXXXX"CONSUMER_SECRET="XXXXXXX"

Double quotes are required.

To avoid these keys showing up in your repository, make sure to exclude the file from being checked in by adding to your .gitignore file:

apikey.properties

Next, add this section to read from this file in your app/build.gradle file. You'll also create compile-time options that will be generated from this file by using the buildConfigField definition:

def apikeyPropertiesFile = rootProject.file("apikey.properties")def apikeyProperties = new Properties()apikeyProperties.load(new FileInputStream(apikeyPropertiesFile)) android { defaultConfig { // should correspond to key/value pairs inside the file  buildConfigField("String", "CONSUMER_KEY", apikeyProperties['CONSUMER_KEY']) buildConfigField("String", "CONSUMER_SECRET", apikeyProperties['CONSUMER_SECRET']) }}

You can now access these two fields anywhere within your source code with the BuildConfig object provided by Gradle:

// inside of any of your application's codeString consumerKey = BuildConfig.CONSUMER_KEY;String consumerSecret = BuildConfig.CONSUMER_SECRET;

Now you have access to as many secret values as you need within your app, but will avoid checking in the actual values into your git repository. To read more about this approach, check out this article or this other article.

Secrets in Resource Files

Start by creating a resource file for your secrets called res/values/secrets.xml with a string pair per secret value:

<!-- Inside of `res/values/secrets.xml` --><?xml version="1.0" encoding="utf-8"?><resources> <string name="parse_application_id">xxxxxx</string> <string name="google_maps_api_key">zzzzzz</string></resources>

Once these keys are in the file, Android will automatically merge it into your resources, where you can access them exactly as you would your normal strings. You can access the secret values in your Java code with:

// inside of an Activity, `getString` is called directlyString secretValue = getString(R.string.parse_application_id);// inside of another class (requires a context object to exist)String secretValue = context.getString(R.string.parse_application_id);

If you need your keys in another XML file such as in AndroidManifest.xml, you can just use the XML notation for accessing string resources:

@string/google_maps_api_key

Since your secrets are now in an individual file, they're simple to ignore in your source control system (for example, in Git, you would add this to the '.gitignore' file in your repository) by entering this on the command line within your project git repository:

echo "**/*/res/values/secrets.xml" > .gitignore

Verification: To make sure this worked, check the .gitignore file within your git repository, and make sure that this line referencing secrets.xml exists. Now, go to commit files to Git and make sure that you do not see the secrets.xml file in the staging area. You do not want to commit this file to Git.

This process is not bulletproof. As resources, they are somewhat more vulnerable to decompilation of your application package, and so they are discoverable if somebody really wants to know them. This solution does, however, prevent your secrets just sitting in plaintext in source control waiting for someone to use, and also has the advantage of being simple to use, leveraging Android's resource management system, and requiring no extra libraries.

However, none of these strategies will ensure the protection of your keys and your secrets aren't safe. The best way to protect secrets is to never reveal them in the code in the first place. Compartmentalizing sensitive information and operations on your own backend server/service should always be your first choice.

If you do have to consider a hiding scheme, you should do so with the realization that you can only make the reverse engineering process harder and may add significant complication to the development, testing, and maintenance of your app in doing so. Check out this excellent StackOverflow post for a detailed breakdown of the obfuscation options available.

The simplest and most straightforward approach is outlined below which is to store your secrets within a resource file. Keep in mind that most of the other more complex approaches above are at best only marginally more secure.

Secrets in native libraries with NDK

Another way to make your keys hard to reverse engineer is to save them in the NDK. A recommanded implementation as done in hidden-secrets-gradle-plugin :

  • secret is obfuscated using the reversible XOR operator so it never appears in plain sight,
  • obfuscated secret is stored in a NDK binary as an hexadecimal array, so it is really hard to spot / put together from a disassembly,
  • the obfuscating string is not persisted in the binary to force runtime evaluation (ie : prevent the compiler from disclosing the secret by optimizing the de-obfuscation logic),
  • optionnaly, anyone can provide it's own encoding / decoding algorithm when using the plugin to add an additional security layer.

Using the Android Keystore API

To understand the Android Keystore API, you must first understand that encrypting secrets requires both public key and symmetric cryptography. In public key cryptography, data can be encrypted with one key and decrypted with the other key. In symmetric cryptography, the same key is used to encrypt and decrypt the data. The Keystore API uses both types of cryptography in order to safeguard secrets.

A public/private key RSA pair is generated, which is stored in the Android device's keystore and protected usually by the device PIN. An AES-based symmetric key is also generated, which is used to encrypt and decrypt the secrets. The app needs to store this AES symmetric key to later decode, so it is encrypted by the RSA public key first before persisted. When the app runs, it gives this encrypted AES key to the Keystore API, which will decode the data using its private RSA key. In this way, data cannot be decoded without the use of the device keystore.

Read this Medium blog for more information about how to use the Keystore API. Do not use the Qlassified Android library because it introduces an additional 20K methods to your Android program. You can use the Android Vault library, which will also help facilitate the rotation of RSA keys, which usually have an expiration date of 1-5 years.

See also the official Google sample for using the Android Keystore.

Resources

Storing Secret Keys in Android (2024)

FAQs

Where to save secret key in Android? ›

If you must store secrets on the device (i.e for biometric authorization), use the Android Keystore system to encrypt sensitive data. Keystore stores cryptographic keys and performs all cryptographic operations on dedicated hardware, separate from the operating system (TEE or SE).

Where to store private key on Android? ›

The Android Keystore system lets you store cryptographic keys in a container to make them more difficult to extract from the device. Once keys are in the keystore, you can use them for cryptographic operations, with the key material remaining non-exportable.

How to securely store API keys on Android? ›

This guide outlines a straightforward process for storing API keys securely in an Android project.
  1. Store your API Keys in the Global gradle. properties file. ...
  2. Modify your app-level build. gradle file. ...
  3. Sync, clean and rebuild the project. ...
  4. Retrieve the key in your code.
Jan 22, 2024

Where to save secret keys? ›

Use secure key management systems (KMS) to store secret keys. When you create a secret live mode key from the Stripe Dashboard, it is only revealed once. Immediately copy the key to a KMS, which is designed to handle sensitive information with encryption and access controls.

Where are encryption keys stored in Android? ›

Keystore keys are stored in the user data partition in the following location: /misc/keystore/ but are usually stored in an encrypted format.

How do I store my private key? ›

Private keys can be stored using a hardware wallet that uses smartcards, USB, or Bluetooth-enabled devices to secure your private keys offline. There are two types of key storage, each with two types of wallets. Custodial wallets are wallets where someone else, like an exchange, stores your keys for you.

Where is the safest place to store private keys? ›

If you're looking for a bulletproof way to store your private keys, then you should go with physical devices such as USB Tokens, Smart Cards, or Hardware Security Module (HSM). With hardware storage devices, the attackers must first gain access to them, which is significantly more unlikely in the real, physical world.

Where is private key saved? ›

The path to your private key is listed in your site's virtual host file. Navigate to the server block for your site (by default, it's located in the /var/www directory). Open the configuration file for your site and search for ssl_certificate_key which will show the path to your private key.

Where is Android keystore located? ›

The first time you run or debug your project in Android Studio, the IDE automatically creates the debug keystore and certificate in $HOME/.android/debug.keystore , and sets the keystore and key passwords.

What is the KeyChain on Android? ›

The KeyChain class provides access to private keys and their corresponding certificate chains in credential storage.

How do you create a keystore in Android? ›

Creating a Keystore File
  1. Select Tools > Options > Environment Options > Provisioning.
  2. In the Build Type field, select the Android - Application Store build type.
  3. Click New Keystore.

What is the best way to store API keys? ›

Keep API keys isolated from the main code and away from the public eye by storing them in environmental variables. Always keep API keys in safe key management solutions for storage. Make sure that the keys are encrypted both in transit and at rest. Alternate your API keys regularly to minimize exposure concerns.

Where should you store encryption keys? ›

Where possible, encryption keys should be stored in a separate location from encrypted data. For example, if the data is stored in a database, the keys should be stored in the filesystem.

Is it safe to store secrets in memory? ›

Often attempting to protect secrets in memory will be considered overkill because as you evaluate a threat model, the potential threat actors that you consider either do not have the capabilities to carry out such attacks or the cost of defense far exceeds the likely impact of a compromise arising from exposing secrets ...

Where do I save my encryption key? ›

You should store your keys in a place that is isolated from the data they protect, and that has restricted access and strong encryption. Some options are hardware security modules (HSMs), cloud key management services (KMSs), or encrypted files or databases.

How do I put a security key on my Android phone? ›

On your Android phone, go to myaccount.google.com/security. Under "How you sign in to Google," select Passkeys and security keys. You might need to sign in. At the bottom left, tap Add security key.

Where is the location of Android debug key? ›

On Windows, if the debug. keystore file is not in the location (C:\Users\username\. android), the debug. keystore file may also be found in the location where you have installed Android Studio.

Where is the best place to store secret files? ›

Use cloud storage like your digital file cabinet. Store private files and synchronize them across devices. Cloud storage is equal parts accessible and secure. If anything happened to your device, restoring data from the cloud is easy.

Top Articles
Islamic Relief USA
Commerce Components by Shopify
Craigslist Pets Longview Tx
Pinellas County Jail Mugshots 2023
Napa Autocare Locator
Miss Carramello
라이키 유출
What happens if I deposit a bounced check?
Shaniki Hernandez Cam
3472542504
180 Best Persuasive Essay Topics Ideas For Students in 2024
Arboristsite Forum Chainsaw
Steamy Afternoon With Handsome Fernando
Bcbs Prefix List Phone Numbers
Telegram Scat
Michael Shaara Books In Order - Books In Order
Toy Story 3 Animation Screencaps
Buy Swap Sell Dirt Late Model
Lowe's Garden Fence Roll
Loves Employee Pay Stub
Chase Bank Pensacola Fl
Dragonvale Valor Dragon
What Is The Lineup For Nascar Race Today
Low Tide In Twilight Ch 52
Hannah Palmer Listal
Essence Healthcare Otc 2023 Catalog
8002905511
Albertville Memorial Funeral Home Obituaries
Elijah Streams Videos
Davita Salary
Star News Mugshots
Mkvcinemas Movies Free Download
Wcostream Attack On Titan
In Polen und Tschechien droht Hochwasser - Brandenburg beobachtet Lage
Case Funeral Home Obituaries
Can You Buy Pedialyte On Food Stamps
Smith And Wesson Nra Instructor Discount
Craigslist Tulsa Ok Farm And Garden
Gateway Bible Passage Lookup
2023 Nickstory
Fedex Passport Locations Near Me
Top 1,000 Girl Names for Your Baby Girl in 2024 | Pampers
Breaking down the Stafford trade
Hawkview Retreat Pa Cost
Costner-Maloy Funeral Home Obituaries
De boeken van Val McDermid op volgorde
Blippi Park Carlsbad
Used Auto Parts in Houston 77013 | LKQ Pick Your Part
Assignation en paiement ou injonction de payer ?
8663831604
Room For Easels And Canvas Crossword Clue
Cataz.net Android Movies Apk
Latest Posts
Article information

Author: Greg Kuvalis

Last Updated:

Views: 6273

Rating: 4.4 / 5 (55 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Greg Kuvalis

Birthday: 1996-12-20

Address: 53157 Trantow Inlet, Townemouth, FL 92564-0267

Phone: +68218650356656

Job: IT Representative

Hobby: Knitting, Amateur radio, Skiing, Running, Mountain biking, Slacklining, Electronics

Introduction: My name is Greg Kuvalis, I am a witty, spotless, beautiful, charming, delightful, thankful, beautiful person who loves writing and wants to share my knowledge and understanding with you.