Chain is null when retrieving private key
<p>I'm encrypting data in my app using a RSA keypair that I am storing in the Android keystore.</p>

<p>I've been seeing <code>NullPointerException</code>s in the Play Store, but I have not been able to reproduce them:</p>

<pre><code>java.lang.NullPointerException: chain == null
    at java.security.KeyStore$PrivateKeyEntry.&lt;init&gt;(KeyStore.java:1205)
    at java.security.KeyStoreSpi.engineGetEntry(KeyStoreSpi.java:374)
    at java.security.KeyStore.getEntry(KeyStore.java:644)
    at MyClass.getKeyStoreEntry(MyClass.java:111)
</code></pre>

<p>The source code to create the key pair</p>

<pre><code>Calendar start = Calendar.getInstance();
start.setTimeInMillis(0);
Calendar end = Calendar.getInstance();
end.set(Calendar.YEAR, 3000);

KeyPairGeneratorSpec.Builder keySpecBuilder = new KeyPairGeneratorSpec.Builder(context)
    .setAlias(keyName)
    .setSubject(new X500Principal("CN=" + keyName))
    .setSerialNumber(BigInteger.TEN)
    .setStartDate(start.getTime())
    .setEndDate(end.getTime())
    .setKeySize(RSA_KEY_SIZE);

KeyPairGeneratorSpec spec = keySpecBuilder.build();
KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
gen.initialize(spec);
gen.generateKeyPair();
</code></pre>

<p>And then to retrieve the key:</p>

<pre><code>private KeyStore.PrivateKeyEntry getKeyStoreEntry() {
    KeyStore keyStore = KeyStore.getInstance(ANDROID_KEY_STORE);
    keyStore.load(null);

    if (!keyStore.containsAlias(keyName)) {
        throw new KeyNotFoundException();
    }
    return (KeyStore.PrivateKeyEntry) keyStore.getEntry(keyName, null);
}
</code></pre>

<p>This is only happening when I make use of the <code>KeyPairGeneratorSpec</code> on API level 19-22. The 23+ implementation works fine.</p>

<p>I <a href="https://stackoverflow.com/questions/23977407/android-4-3-keystore-chain-null-while-trying-to-retrieve-keys">do not have another key with the same name</a> and I also have not <a href="https://stackoverflow.com/questions/37094464/android-keystore-issue-keystore-getentryalias-null-returns-null-sometimes">deleted the key</a>.</p>