使用AndroidKeyStore身份验证的无限循环

ped*_*ofb 5 android infinite-loop digital-signature android-keystore

当我使用需要用户身份验证才能使用密钥的 AndroidKeyStore 时,我的应用程序进入无限循环

.setUserAuthenticationRequired(true);
.setUserAuthenticationValidityDurationSeconds(60);
Run Code Online (Sandbox Code Playgroud)

假设使用用户私钥的操作要求设备已解锁,否则UserNotAuthenticatedException生成a。应用程序必须显示设备身份验证屏幕,并且密钥的下次使用才会起作用。

但是,就我而言,总是会强制UserNotAuthenticatedException应用程序显示解锁屏幕。它仅发生在某些设备中。我有两台运行 Android 6.0.1 的 Nexus 5,只有其中一台出现故障。

这是活动的主要代码

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

以及生成密钥的代码

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;
}
Run Code Online (Sandbox Code Playgroud)