security-samples icon indicating copy to clipboard operation
security-samples copied to clipboard

When upgrading AGP from version 7.2.2 to 7.3.1, the implementation I had for detecting if there was a change in the biometric (e.g. adding a new fingerprint) does not work.

Open juacosoft opened this issue 1 year ago • 1 comments

When upgrading AGP from version 7.2.2 to 7.3.1, the implementation I had for detecting if there was a change in the biometric (e.g. adding a new fingerprint) does not work. In AGP 7.2.2, it detects the change and throws a KeyPermanentlyInvalidatedException when cipher.apply { init(Cipher.ENCRYPT_MODE, secretKey) }


val secretKey = getSecretKey()

return try {
    cipher.apply { init(Cipher.ENCRYPT_MODE, secretKey) }
} catch (error: KeyPermanentlyInvalidatedException) {
    // do something
} 

private fun getSecretKey(): SecretKey {
    val keyStore = KeyStore.getInstance(KEY_ANDROID_STORE).apply {
        load(null)
    }
    if (!isKeyExists(keyStore)) {
        createSecretKey()
    }
    return keyStore.getKey(KEY_NAME, null) as SecretKey
}

private fun createSecretKey() {
    generateSecretKey(
        KeyGenParameterSpec.Builder(KEY_NAME, PURPOSE_ENCRYPT or PURPOSE_DECRYPT)
            .setBlockModes(BLOCK_MODE_CBC)
            .setEncryptionPaddings(ENCRYPTION_PADDING_PKCS7)
            .setUserAuthenticationRequired(true)
            .setInvalidatedByBiometricEnrollment(true)
            .build()
    )
}

private fun generateSecretKey(keyGenParameterSpec: KeyGenParameterSpec): SecretKey? {
    val keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM_AES, KEY_ANDROID_STORE)
    keyGenerator.init(keyGenParameterSpec)
    return keyGenerator.generateKey()
}

private fun isKeyExists(keyStore: KeyStore): Boolean {
    val aliases = keyStore.aliases()
    while (aliases.hasMoreElements()) {
        return KEY_NAME == aliases.nextElement()
    }
    return false
}
// `....`
biometric info config
setAllowedAuthenticators(BIOMETRIC_STRONG)

juacosoft avatar Mar 31 '23 00:03 juacosoft

Open

Samric24 avatar Aug 23 '23 02:08 Samric24