Android: 如何在生成后立即使用指纹保护密钥进行加密?

Android: How do I encrypt with fingerprint protected secret key right after generating it?

我正在尝试使用我的指纹加密 PIN。我的计划是在我的设置 activity 中进行设置以激活指纹保护。

一旦用户打开设置,he/she 将被要求输入他们的 PIN,然后使用链接到他们指纹的密钥对其进行加密。

根据 Google's android-FingerprintDialog sample,我创建了一个链接到我的指纹的密钥,并在生成它来加密我的 PIN 码后立即尝试使用它,但我在调用 android.security.KeyStoreException: Key user not authenticated 时收到 android.security.KeyStoreException: Key user not authenticated =13=].

看来我不仅要让用户输入 PIN,还要让他们用指纹验证一次以加密 PIN,这有点影响用户体验。

有没有什么方法可以在生成 PIN 码后立即使用密钥加密,而无需用户在第一次进行身份验证?

请看下面我的代码。谢谢。

    public void createKey(String keyName, boolean invalidatedByBiometricEnrollment) {
        // The enrolling flow for fingerprint. This is where you ask the user to set up fingerprint
        // for your flow. Use of keys is necessary if you need to know if the set of
        // enrolled fingerprints has changed.
        try {
            mKeyStore.load(null);
            // Set the alias of the entry in Android KeyStore where the key will appear
            // and the constrains (purposes) in the constructor of the Builder

            KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(keyName,
                    KeyProperties.PURPOSE_ENCRYPT |
                            KeyProperties.PURPOSE_DECRYPT)
                    .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                    // Require the user to authenticate with a fingerprint to authorize every use
                    // of the key
                    .setUserAuthenticationRequired(true)
                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7);

            // This is a workaround to avoid crashes on devices whose API level is < 24
            // because KeyGenParameterSpec.Builder#setInvalidatedByBiometricEnrollment is only
            // visible on API level +24.
            // Ideally there should be a compat library for KeyGenParameterSpec.Builder but
            // which isn't available yet.
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                builder.setInvalidatedByBiometricEnrollment(invalidatedByBiometricEnrollment);
            }
            mKeyGenerator.init(builder.build());
            SecretKey secretKey = mKeyGenerator.generateKey();

            if (initEncryptionCipher(mDefaultEncryptionCipher, secretKey))
                tryEncrypt(mDefaultEncryptionCipher, SECRET_MESSAGE);
        } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException
                | CertificateException | IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Initialize the {@link Cipher} instance with the created key in the
     * {@link #createKey(String, boolean)} method.
     *
     * @param secretKey the key name to init the cipher
     * @return {@code true} if initialization is successful, {@code false} if the lock screen has
     * been disabled or reset after the key was generated, or if a fingerprint got enrolled after
     * the key was generated.
     */
    private boolean initEncryptionCipher(Cipher cipher, SecretKey secretKey) {
        try {
            mKeyStore.load(null);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            return true;
        } catch (KeyPermanentlyInvalidatedException e) {
            Log.e("Encryption Cipher", Log.getStackTraceString(e));
            return false;
        } catch (CertificateException | IOException
                | NoSuchAlgorithmException | InvalidKeyException e) {
            throw new RuntimeException("Failed to init Cipher", e);
        }
    }


    /**
     * Tries to encrypt some data with the generated key in {@link #createKey} which is
     * only works if the user has just authenticated via fingerprint.
     */
    private void tryEncrypt(Cipher cipher, String secret) {
        try {
            byte[] encrypted = cipher.doFinal(secret.getBytes());
            SECRET_MESSAGE = new String(Base64.encode(encrypted, Base64.DEFAULT));
        } catch (BadPaddingException | IllegalBlockSizeException e) {
            Toast.makeText(this, "Failed to encrypt the data with the generated key. "
                    + "Retry the purchase", Toast.LENGTH_LONG).show();
            Log.e(TAG, Log.getStackTraceString(e));
        }
    }

setUserAuthenticationRequired(true) 没有指定有效期意味着:

Each operation involving such a key must be individually authorized by the user. Currently, the only means of such authorization is fingerprint authentication

这包括创建密钥后的第一个操作。


KeyGenParameterSpec.Builder 有另一种方法,setUserAuthenticationValidityDurationSeconds 允许您指定密钥在最近一次授权后的 N 秒内可用于无限次操作。您为其指定有效期的密钥也略有不同 属性:

All keys in this mode are authorized for use as soon as the user unlocks the secure lock screen or confirms their secure lock screen credential using the KeyguardManager.createConfirmDeviceCredentialIntent flow

但是,我不知道这是否适用于新创建的密钥 - 即新创建的密钥是否立即可用,或者直到 下一个用户解锁屏幕的时间。


(source)