mKeyStore?.getKey(“ default_key”,null)在Kotlin中为null

时间:2019-08-01 07:15:50

标签: java android kotlin keystore android-fingerprint-api

我在Android中尝试过指纹验证器。最初它正在运行,并且使用Java。现在我将代码移植到kotlin。这次有些东西对我不起作用。

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);

上面编写的代码是用Java编写的,我得到的键为非null值。

但是当用Kotlin编写相同的代码时,密钥将得到一个空值。

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

我为什么要得到这个?请告诉我是否有任何遗漏。

感谢您的宝贵时间。

1 个答案:

答案 0 :(得分:1)

初始化密钥生成器,然后提取密钥。

Notice: Constant BASEURL already defined in C:\xampp\htdocs\medassist\core\init.php on line 8