When AndroidKeyStore stores Private and Public keys in AndroidKeyStore?

715 views Asked by At

Which method stores Private and Public keys in AndroidKeyStore?

I have implemented below code to initialise keystore and generate private and public keys.

KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);

KeyPair keyPair;
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
end.add(Calendar.YEAR, 50);

KeyPairGenerator generator= KeyPairGenerator.getInstance("RSA","AndroidKeyStore");

KeyPairGeneratorSpec keyPairGeneratorSpec = new KeyPairGeneratorSpec.Builder(context).
                        setAlias("alias").
                        setSubject(new X500Principal("O=Authority")).
                        setSerialNumber(BigInteger.ONE).
                        setStartDate(start.getTime()).
                        setEndDate(end.getTime()).build();


if (generator != null) {
      generator.initialize(keyPairGeneratorSpec);
}
keyPair = generator.generateKeyPair();
2

There are 2 answers

0
divegeek On

When you generate a key pair with AndroidKeyStore, it is already automatically stored. You can retrieve it when you need it using the alias you specified ("alias" in your example).

Note, however, that when you get the PrivateKey, you do not actually get the private key secrets. Those stay in secure hardware and never leave it, so they can't leak. But you get a PrivateKey object which you can use just as though you had the secrets; your requests to encrypt or sign are sent to the secure hardware, which uses the secrets to perform the operation and hands the result back to you.

0
刘宇翔 On

To your question, this line generator.generateKeyPair(); implement the keypair generating and storing processs.

You might be confused when seeing codes in java.security.KeyPairGenerator like this
public KeyPair generateKeyPair() { // ... return null; }

But actually since KeyPairGenerator is an abstract class, the 'true' class here using is java.security.KeyPairGenerator$Delegate, which delegates the generateKeyPair like this

You can also check the difference of alias list in "AndroidKeyStore" before and after this process.

I would like to share the gist about how to view alias list of any keystore. Hope it might help you testing: https://gist.github.com/davidkhala/4aa1d6b44f287699aeac028786633c7a