Bucle infinito usando la autenticación de AndroidKeyStore
Mi aplicación entra en un bucle infinito cuando uso AndroidKeyStore que requiere autenticación de usuario para usar las teclas
.setUserAuthenticationRequired(true);
.setUserAuthenticationValidityDurationSeconds(60);
Se supone que una operación que utiliza la clave privada de un usuario requiere que el dispositivo se haya desbloqueado; de lo contrario,UserNotAuthenticatedException
es generado. La aplicación debe presentar la pantalla de autenticación del dispositivo, y el próximo uso de la clave funcionará.
Pero, en mi caso siempre se tiraUserNotAuthenticatedException
forzando a la aplicación a mostrar la pantalla de desbloqueo. Solo sucede en algunos dispositivos. Tengo dos Nexus 5 con Android 6.0.1 y solo falla en uno de ellos.
Este es el código principal de la actividad.
KeyPair keyPair;
private void attemptRegisterKey(){
try{
//generate key pair using AndroidKeyStore only once.
if (keyPair != null)
generateKeyPair(alias);
//Sample Signature
Signature sig = Signature.getInstance("SHA256withRSA");
sig.initSign(keyPair.getPrivate());
sig.update("hello".getBytes());
byte signature[] = sig.sign();
}catch (UserNotAuthenticatedException e){
//show Authentication Screen
Intent intent = mKeyguardManager.createConfirmDeviceCredentialIntent(null, null);
startActivityForResult(intent, REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS) {
// Challenge completed, proceed
if (resultCode == RESULT_OK) {
attemptRegisterKey();
} else {
//Process error
}
}
}
Y el código para generar la clave
public KeyPair generateKeyPair(String alias) throws Exception {
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
KeyPairGenerator kpg = KeyPairGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(
alias,
KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY)
.setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
.setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
.setUserAuthenticationRequired(true);
.setUserAuthenticationValidityDurationSeconds(60);
kpg.initialize(builder.build());
KeyPair kp = kpg.generateKeyPair();
return kp;
}