0

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

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

4

1 回答 1

0

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

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

这是一些使用新的示例代码KeyGenParameterSpec(来自这里):

/**
 * 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);
    }
}
于 2016-05-09T15:54:26.903 回答