Friday, 8 October 2021

KeyStore.getCertificate(alias) returns null sometimes

Background

I am developing an Android app.
For some use case, I need to make use of the AndroidKeyStore and save a NIST P-256 (aka secp256r1 aka prime256v1) EC key pair.

After generating the key pair, I need to retrieve the public key later to use.

What I wrote

For generating the key pair:

        val generator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore")
        val spec = KeyGenParameterSpec
                .Builder("alias", KeyProperties.PURPOSE_SIGN)
                .setAlgorithmParameterSpec(ECGenParameterSpec("secp256r1"))
                .setDigests(KeyProperties.DIGEST_SHA256)
                .build()
        generator.initialize(spec)
        generator.generateKeyPair()

For retrieving the public key:

    val keyStore = KeyStore.getInstance("AndroidKeyStore")
    keyStore.load(null)
    return keyStore.getCertificate("alias").publicKey

The problem

I observed that about 10~15% of our users are reporting that keyStore.getCertificate("alias") is null, which therefore throws a NullPointerException, but I cannot figure out why...

Observations

  1. Same device model cannot reproduce the same problem
  2. Changing KeyProperties.PURPOSE does not work

The Question

What are the possible reasons of getting null when I call getCertificate, even if I have generate a key pair with the same alias before?



from KeyStore.getCertificate(alias) returns null sometimes

No comments:

Post a Comment