KeyGenerator初始化(Marshmallow)上的UnsupportedOperationException

时间:2015-10-22 10:01:09

标签: android security cryptography

在Android 6.0中,我们有更改,比如BoringSSL库,它取代了OpenSSL。

在我的代码中,我对KeyGenerator进行了初始化:

keyGenerator = KeyGenerator.getInstance(algorithm)
keyGenerator.init(256);

这适用于Android 6.0版,但在Marshmallow中它会返回:

java.lang.UnsupportedOperationException: Cannot initialize without a android.security.keystore.KeyGenParameterSpec parameter

如何在这些设备中启动密钥生成器?

1 个答案:

答案 0 :(得分:1)

使用SDK 23和Android M的特定代码解决:

 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        builder = new KeyGenParameterSpec.Builder("key1",
                KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT);
        KeyGenParameterSpec keySpec = builder
                .setKeySize(256)
                .setBlockModes("CBC")
                .setEncryptionPaddings("PKCS7Padding")
                .setRandomizedEncryptionRequired(true)
                .setUserAuthenticationRequired(true)
                .setUserAuthenticationValidityDurationSeconds(5 * 60)
                .build();
        try {
            this.keyGenerator.init(keySpec);
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        }

    } else {
        // Default KeyGenerator initialization
    }