首页 > 解决方案 > Android:如何在生成后立即使用受指纹保护的密钥进行加密?

问题描述

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

一旦用户打开设置,他/她将被要求输入他们的 PIN,然后将使用与他们的指纹相关联的密钥对其进行加密。

根据Google 的 android-FingerprintDialog 示例,我创建了一个链接到我的指纹的密钥,并在生成它后立即尝试使用它来加密我的 PIN,但我android.security.KeyStoreException: Key user not authenticated在调用时得到了cipher.doFinal()

看来我不仅要要求用户输入 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));
        }
    }

标签: androidsecurityencryptionfingerprint

解决方案


setUserAuthenticationRequired(true)没有指定有效期是指:

涉及此类密钥的每个操作都必须由用户单独授权。目前,这种授权的唯一方式是指纹认证

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


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

一旦用户解锁安全锁定屏幕或使用KeyguardManager.createConfirmDeviceCredentialIntent流程确认其安全锁定屏幕凭据,此模式下的所有密钥都会被授权使用

但是,我不知道这是否适用于新创建的密钥 - 即新创建的密钥是否立即可用,或者直到用户下次解锁屏幕时才会发生这种情况。


来源


推荐阅读