Android Keystore Provider - How to Store an API Key

In my android app I am getting API token which I am getting from http request

I did some research, and if this is the best way to store this key, this is the Keystore Android app.

I looked at the documentation https://developer.android.com/training/articles/keystore.html#UsingAndroidKeyStore

But since I am new to Android and programming in general, I need help getting this into place.

I'm not sure which variable I should store the key in:

Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
cal.add(Calendar.YEAR, 1);
Date end = cal.getTime();

KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
kpg.initialize(new KeyPairGeneratorSpec.Builder(getApplicationContext())
    .setAlias(alias)
    .setStartDate(now)
    .setEndDate(end)
    .setSerialNumber(BigInteger.valueOf(1))
    .setSubject(new X500Principal("CN=test1"))
    .build());

KeyPair kp = kpg.generateKeyPair();

      

Then how should I extract the key using (I think) the following code:

KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
ks.load(null);
Enumeration<String> aliases = ks.aliases();

      

Thank you for your help.

+3


source to share


1 answer


I would assume that your API token is only valid for a certain period of time. Just save it in SharedPreferences

for your application. If it's not there, or it's expired, just get another one.



+1


source







All Articles