创建KeyPairGeneratorSpec的实例

时间:2016-05-09 15:40:01

标签: android android-keystore key-pair

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

通常,我需要创建一个带密钥大小的KeyPairGeneratorSpec。现在该怎么办?

1 个答案:

答案 0 :(得分:0)

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

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

以下是使用新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);
    }
}