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

时间:2018-05-05 10:30:25

标签: android security encryption fingerprint

我正在尝试使用指纹加密PIN码。我的计划是在我的“设置”活动中设置一个设置以激活指纹保护。

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

根据Google's android-FingerprintDialog sample,我创建了一个链接到我的指纹的密钥,并且在生成它以加密我的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));
        }
    }

1 个答案:

答案 0 :(得分:1)

未指定有效期的

setUserAuthenticationRequired(true)表示:

  

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

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

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

  

只要用户解锁安全锁定屏幕或使用KeyguardManager.createConfirmDeviceCredentialIntent流程

确认其安全锁定屏幕凭据,就可以使用此模式下的所有密钥

但是,我不知道这是否适用于新创建的密钥 - 即新创建的密钥是否立即可用,或者是否在 next 时间之前不会发生用户解锁屏幕。

source