Search code examples
javaandroidkotlinkeystoreandroid-fingerprint-api

mKeyStore?.getKey("default_key", null) is getting null in Kotlin


I have tried a fingerprint authenticator in Android. And initially it is working and that was in Java. And I am now porting the code to kotlin. This time something is not working for me.

try {
        mKeyStore = KeyStore.getInstance("AndroidKeyStore");
    } catch (KeyStoreException e) {
        throw new RuntimeException("Failed to get an instance of KeyStore", e);
    }
    try {
        mKeyGenerator = KeyGenerator
                .getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
        throw new RuntimeException("Failed to get an instance of KeyGenerator", e);
    }    

mKeyStore.load(null);
SecretKey key = (SecretKey) mKeyStore.getKey("default_key", null);

Above written code is in Java and I get key as non-null value.

But when the same code is written in Kotlin the key is getting a null value.

try {
    mKeyStore = KeyStore.getInstance("AndroidKeyStore")
} catch (e: KeyStoreException) {
    throw RuntimeException("Failed to get an instance of KeyStore", e)
}

try {
    mKeyGenerator = KeyGenerator
        .getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
} catch (e: NoSuchAlgorithmException) {
    throw RuntimeException("Failed to get an instance of KeyGenerator", e)
} catch (e: NoSuchProviderException) {
    throw RuntimeException("Failed to get an instance of KeyGenerator", e)
}

mKeyStore?.load(null)
val key = mKeyStore?.getKey("default_key", null) as? SecretKey

Why I am getting this? Clarify me If anything is missing.

Thank you for your valuables time.


Solution

  • Initialize the keygenerator and then extract the secretkey.

     mKeyGenerator.init(
            KeyGenParameterSpec.Builder("default_key", KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
                .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                .setUserAuthenticationRequired(true)
                .setEncryptionPaddings(
                    KeyProperties.ENCRYPTION_PADDING_PKCS7
                )
                .build()
        )
        mKeyGenerator.generateKey()