问题
My application enters an infinite loop when I use the AndroidKeyStore requiring user authentication to use the keys
.setUserAuthenticationRequired(true);
.setUserAuthenticationValidityDurationSeconds(60);
It is assumed that an operation that uses a user's private key requires that the device has been unlocked, otherwise a UserNotAuthenticatedException
is generated. The app must present the device authentication screen, and the next usage of the key will work.
But, in my case always is thrown UserNotAuthenticatedException
forcing app to show the unlock screen. It only happens in some devices. I have two Nexus 5 with Android 6.0.1 and only fails in one of them.
This is the main code of the activity
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
}
}
}
And the code to generate the key
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;
}
来源:https://stackoverflow.com/questions/47920995/infinite-loop-using-androidkeystore-authentication