android - Why does android BiometricPrompt authentication bound encryption throws IllegalBlockSizeException
问题描述
I am quite unsuccessfully trying to implement BiometricPrompt with authentication bound decryption key(without allowing pin/password/pattern alternatives). I am using asymmetric keys since I need to encrypt a string without user authentication and decrypt the string with user authentication required. However, when I try to use the cryptoObject provided by BiometricPrompt to the onAuthenticationSucceeded callback I get IllegalBlockSizeException nullcode = 100104. If I simply set the setUserAuthenticationRequired to false everything works just fine without exception. If there would be anything wrong with authentication wouldn't i get a UserNotAuthenticatedException? And if there would be anything wrong with encryption wouldn't I get the IllegalBlockSizeException no matter setUserAuthenticationRequired. What is the source of this IllegalBlockSizeException? and how can i solve it?
Encoding:
fun encode(
keyAlias: String,
decodedString: String,
isAuthorizationRequired: Boolean
): String {
val cipher: Cipher = getEncodeCipher(keyAlias, isAuthorizationRequired)
val bytes: ByteArray = cipher.doFinal(decodedString.toByteArray())
return Base64.encodeToString(bytes, Base64.NO_WRAP)
}
//allow encoding without user authentication
private fun getEncodeCipher(
keyAlias: String,
isAuthenticationRequired: Boolean
): Cipher {
val cipher: Cipher = getCipherInstance()
val keyStore: KeyStore = loadKeyStore()
if (!keyStore.containsAlias(keyAlias))
generateKey(keyAlias, isAuthenticationRequired
)
//from https://developer.android.com/reference/android/security/keystore/KeyGenParameterSpec.html
val key: PublicKey = keyStore.getCertificate(keyAlias).publicKey
val unrestricted: PublicKey = KeyFactory.getInstance(key.algorithm).generatePublic(
X509EncodedKeySpec(key.encoded)
)
val spec = OAEPParameterSpec(
"SHA-256", "MGF1",
MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT
)
cipher.init(Cipher.ENCRYPT_MODE, unrestricted, spec)
return cipher
}
key generation:
private fun generateKey(keyAlias: String, isAuthenticationRequired: Boolean) {
val keyGenerator: KeyPairGenerator = KeyPairGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore"
)
keyGenerator.initialize(
KeyGenParameterSpec.Builder(
keyAlias,
KeyProperties.PURPOSE_DECRYPT or KeyProperties.PURPOSE_ENCRYPT
).run {
setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP)
setUserAuthenticationRequired(isAuthenticationRequired) //only if isAuthenticationRequired is false -> No IllegalBlockSizeException during decryption
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
setInvalidatedByBiometricEnrollment(true)
}
build()
}
)
keyGenerator.generateKeyPair()
}
}
Decode:
//this Cipher is passed to the BiometricPrompt
override fun getDecodeCipher(keyAlias: String): Cipher {
val keyStore: KeyStore = loadKeyStore()
val key: PrivateKey = keyStore.getKey(keyAlias, null) as PrivateKey
cipher.init(Cipher.DECRYPT_MODE, key)
return cipher
}
//this is called from inside onAuthenticationSucceeded BiometricPrompt.AuthenticationCallback
fun decodeWithDecoder(encodedStrings: List<String>, cryptoObject: BiometricPrompt.CryptoObject): List<String> {
return try {
encodedStrings.map {
val bytes: ByteArray = Base64.decode(it, Base64.NO_WRAP)
//here i get IllegalBlockSizeException after the first iteration if isAuthenticationRequired is set to true
String(cryptoObject.cipher!!.doFinal(bytes))
}
}
BiometricPrompt:
private fun setUpBiometricPrompt() {
executor = ContextCompat.getMainExecutor(requireContext())
val callback = object : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
super.onAuthenticationError(errorCode, errString)
Log.d("${this.javaClass.canonicalName}", "onAuthenticationError $errString")
}
override fun onAuthenticationFailed() {
super.onAuthenticationFailed()
Log.d("${this.javaClass.canonicalName}", "Authentication failed")
}
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
//passing the received crypto object on for decryption operation (which then fails)
decodeWithDecoder(encodedString: String, result.cryptoObject)
super.onAuthenticationSucceeded(result)
}
}
promptInfo = BiometricPrompt.PromptInfo.Builder()
.setTitle("Biometric login for my app")
.setSubtitle("Log in using your biometric credential")
.setNegativeButtonText("Use account password")
.build()
biometricPrompt = BiometricPrompt(this, executor, callback)
}
//show the prompt
fun authenticate() {
biometricPrompt.authenticate(
promptInfo,
BiometricPrompt.CryptoObject(getDecodeCipher()))
}
解决方案
我意识到我最初的代码示例中缺少一个相当重要的细节。实际上,我尝试使用 cryptoObec 中的密码进行多种加密操作。我在上面的示例中添加了该细节,因为这显然是异常的原因。因此,答案显然是如何在密钥上设置 setUserAuthenticationRequired 会影响一次可以使用(一次性)初始化密码对象的频率。如果设置为 false,您可以多次使用 is,而设置为 true 时只能使用一次。或者我在这里错过了什么?当然,问题仍然存在,如何使用用户身份验证绑定密钥解密多个字符串?其他人在 Android 上有类似的问题 - 使用指纹扫描仪和密码来加密和解密多个字符串
推荐阅读
- javascript - 如何防止在 React 中使用纯子级重新渲染纯组件?
- python - 我需要用泡菜来保存字典
- java - Spring Data 中的 Pageable + @Query + JOIN (fetch?) 不起作用
- python - 定制词汇的一种热编码
- python - Python:如何在不耗尽内存的情况下提取 Google Cloud Storage 中的 Zip 文件?
- reactjs - React Suspense 没有按预期工作
- node.js - 将远程文件传递到 Node.js 应用程序中的 libreoffice-convert 库时收到“错误:没有这样的文件或目录,打开”
- autodesk-forge - 无法获取 /api/forge/oauth/callback
- python - 使用 pd.read_html 复制表
- python - POST 方法不适用于 Flask 应用程序 - 错误 404