Following this blog, I'm using this code to create and store a KeyPair
in Android KeyStore:
Context ctx = getApplicationContext();
Calendar notBefore = Calendar.getInstance();
Calendar notAfter = Calendar.getInstance();
notAfter.add(1, Calendar.YEAR);
KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(ctx).
setAlias(RSA_KEYS_ALIAS).setSubject(
new X500Principal(String.format("CN=%s, OU=%s",
getApplicationName(), ctx.getPackageName()))).
setSerialNumber(BigInteger.ONE).
setStartDate(notBefore.getTime()).setEndDate(notAfter.getTime()).build();
KeyPairGenerator kpGenerator;
try {
kpGenerator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
kpGenerator.initialize(spec);
kpGenerator.generateKeyPair();
} catch (Exception e) {
showException(e);
}
When I try to retrieve public key from the KeyStore using this code, a NullPointerException
with the message chain == null
is thrown.
public RSAPublicKey getRSAPublicKey() {
RSAPublicKey result = null;
try {
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
KeyStore.PrivateKeyEntry keyEntry =
(KeyStore.PrivateKeyEntry) keyStore.getEntry(RSA_KEYS_ALIAS, null); // --< exception is thrown here
result = (RSAPublicKey) keyEntry.getCertificate().getPublicKey();
}
} catch (Exception e) {
showException(e);
}
return result;
}
The same goes with the the code to retrieve private key.
Update:
I compared my code with Google BasicAndroidKeyStore sample. The mechanism to generate, store and retrieve the key pair in that sample is virtually the same to what I've implemented. I'm puzzled as to why this code has stopped functioning after a few months of perfectly working.
Any suggestions or hints would be appreciated.