Android How to Secure Api Key

Oct 5, 2019

There is a few things you could take notes of.

NOTE: Nothing is quite 100% safe, but just making it harder for the hacker.

Enable Proguard

It obfuscates the code which make it harder to read when decompiled.

Obfuscate/Encrypt the API Key

It create more work for the hacker to reverse engineer you code to unofuscate the API Key.

DexGuard

Use commercial tool like DexGuard to enable additional string and class encryption.

NDK

Some mentioned NDK is harder to decompiled, thus we can store the API Key in NDK. But I suspect the hacker could easily find the C library and call the relevant function to retrieve the API Key.

To make it harder, make the function to verify a security token argument before returning the API key. Instead of returning the API Key, the function return an Encryption Key which is used to decrypt the API key.

Access API Key from Server

Store the API Key in server and access it during runtime, assuming you implemented proper authentication when communicating with the server.

Could consider Firebase Authentication together with Firestore or Cloud Functions.

Another possibility is Firebase Remote Config.

You should probably encrypt the API Key.

NOTE: The obvious downside is that you can't access the API Key without Internet Access, and you probably need secure storage to store the API key after retrieval.

API Key/Password Storage

Don't store API Key/Password in Shared Preferences. Use EncryptedSharedPreferences (API 23) or KeyStore (API 18 or API 23 for AES support)

Git

If you are using git, remmeber not to check in your API key.

Google API Key

If you are Google API Key, restrict it.

  • Application restrictions: Android apps
  • Restrict usage to your Android apps: put in Package name and SHA-1 certificate fingerprint.
  • API restrictions: Restrict key, and select the APIs to enable.

NOTE: Android, iOS, Web, Backend Server should use separate API key with appropriate restrictions for each.

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.