Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 842
user2230304 Avatar asked Jan 01 '26 09:01

user2230304


1 Answers

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.

like image 200
David Wasser Avatar answered Jan 05 '26 21:01

David Wasser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!