我尝试了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中,我将键作为非零值。
但是,当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
为什么我得到这个?澄清我是否缺少任何东西。
谢谢您的宝贵时间。
初始化键机,然后提取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()