Home » Android » How to securely store access token and secret in Android?

How to securely store access token and secret in Android?

Posted by: admin November 30, 2017 Leave a comment


I am going to use oAuth to fetch mails and contacts from google. I don’t want to ask the user each time to log in to obtain an access token and secret. From what I understood, I need to store them with my application either in a database or SharedPreferences. But I am a bit worried about security aspects with that. I read that you can encrypt and decrypt the tokens but it is easy for an attacker to just decompile your apk and classes and get the encryption key.
What’s the best method to securely store these tokens in Android?


Store them as shared preferences. Those are by default private, and other apps cannot access them. On a rooted devices, if the user explicitly allows access to some app that is trying to read them, the app might be able to use them, but you cannot protect against that. As for encryption, you have to either require the user to enter the decrypt passphrase every time (thus defeating the purpose of caching credentials), or save the key to a file, and you get the same problem.

There are a few benefits of storing tokens instead of the actual username password:

  • Third party apps don’t need to know the password and the user can be sure that they only send it to the original site (Facebook, Twitter, Gmail, etc.)
  • Even if someone steals a token, the don’t get to see the password (which the user might be using on other sites too)
  • Tokens generally have a lifetime and expire after a certain time
  • Tokens can be revoked if you suspect they have been compromised

You can store them in AccountManager. It’s considered best practice according to these guys.

enter image description here

Here’s the official definition:

This class provides access to a centralized registry of the user’s
online accounts. The user enters credentials (username and password)
once per account, granting applications access to online resources
with “one-click” approval.

For detailed guide on how to use AccountManager:

However, in the end AccountManager only stores your token as a plain text. So, I would suggest encrypting your secret before storing them in AccountManager. You can utilize various Encryption library like AESCrypt or AESCrypto

Another option is to use Conceal library. It’s safe enough for Facebook and much easier to use than AccountManager. Here’s a code snippet to save a secret file using Conceal.

byte[] cipherText = crypto.encrypt(plainText);
byte[] plainText = crypto.decrypt(cipherText);

Hope that’s helps.


Well you can secure you access token by fallowing two options.

  1. Use save your access token into android keystore that would not be reverse.
  2. Use NDK function with some calculation that save your token and NDK with c++ code that is very hard to reverse