【问题标题】:Create a instance of KeyPairGeneratorSpec创建 KeyPairGeneratorSpec 的实例
【发布时间】:2016-09-04 07:57:01
【问题描述】:

我需要创建一个 android KeyPairGeneratorSpec 的实例,以前可以使用这个 builder 类,但它在 API 23 中已被弃用。那么,现在创建它的正确方法是什么?

一般来说,我需要创建一个带有密钥大小的KeyPairGeneratorSpec。现在怎么办?

【问题讨论】:

    标签: android android-keystore key-pair


    【解决方案1】:

    KeyPairGeneratorSpec 已被弃用,取而代之的是 KeyGenParameterSpec。

    我不一定会因为 KeyPairGeneratorSpec 已弃用而转而使用 KeyGenParameterSpec,因为如果您想避免使用已弃用的类并保持向后兼容性,则必须为两者编写单独的代码路径同一时间。

    下面是一些使用新的KeyGenParameterSpec(来自here)的示例代码:

    /**
     * Creates a symmetric key in the Android Key Store which can only be used after the user has
     * authenticated with fingerprint.
     */
    public void createKey() {
        // 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 {
            // Set the alias of the entry in Android KeyStore where the key will appear
            // and the constrains (purposes) in the constructor of the Builder
            mKeyGenerator = KeyGenerator.getInstance(
                    KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
            mKeyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME,
                    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)
                    .build());
            mKeyGenerator.generateKey();
        } catch (NoSuchProviderException | NoSuchAlgorithmException | InvalidAlgorithmParameterException e) {
            throw new RuntimeException(e);
        }
    }
    

    【讨论】:

    • 您好,谢谢,我明天试一试,然后接受您的回答:)
    • 我不明白你为什么说“我不一定会因为 KeyPairGeneratorSpec 已被弃用而转向使用 KeyGenParameterSpec”,如果它被弃用,是不是你无论如何都需要拥有较新操作系统(api 23+)的另一个代码路径,因为 KeyPairGeneratorSpec 已被弃用,这意味着它在 Android 6.0+ 中不可用?
    • @Leem.fin,不,deprecated 并不意味着它不可用 - 只是you're recommended not to use it 因为他们希望您使用另一种(更好的)方法。他们可能会在未来的版本中删除它,但deprecated 只是一个提示,试图引导开发人员停止使用它。如果遵循最佳实践,那么您应该尝试停止使用 deprecated 类,否则您可能会在将来更新您的目标 sdk 并发现它不再受支持。
    猜你喜欢
    • 2015-10-08
    • 2012-08-28
    • 2012-08-28
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    • 2018-01-22
    相关资源
    最近更新 更多