当前位置: 代码迷 >> Android >> KeyGenerator初始化时出现UnsupportedOperationException(棉花糖)
  详细解决方案

KeyGenerator初始化时出现UnsupportedOperationException(棉花糖)

热度:30   发布时间:2023-08-04 11:01:28.0

在Android 6.0中,我们进行了更改,例如BoringSSL库,它取代了OpenSSL。

在我的代码中,我有一个KeyGenerator的初始化:

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

这可以在Android 6.0之前的版本中使用,但在棉花糖中它将返回:

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

如何在这些设备中初始化我的密钥生成器?

通过使用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
    }