user2230304
user2230304

Reputation: 578

Android Keystore Provider - How to store an API key

In my android app, I receive an API token that I get from an http request

I did some research, and, If it seems the best way to store this key, is with the Android Keystore Provider.

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

But since i'm new with Android and programing in general, I need some help to put that in place.

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

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 retrieve 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.

Upvotes: 3

Views: 1437

Answers (1)

David Wasser
David Wasser

Reputation: 95618

I would assume that your API token is only valid for a certain period of time. Just store it in a SharedPreferences for your application. If it isn't there, or it has expired, just get another one.

Upvotes: 1

Related Questions