KeyPairGeneratorSpec已过时

9

KeyPairGeneratorSpec 在API 23中已经被弃用。您该如何处理这个警告?

示例代码:

KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
kpg.initialize(new KeyPairGeneratorSpec.Builder(context).build());

我的意思是我现在使用Kotlin进行开发,但这些警告仍然存在:D - CoDe
2个回答

10

根据文档,你应该使用KeyGenParameterSpec而不是KeyPairGeneratorSpec.Builder。例如(对于RSA签名密钥):

KeyPairGenerator kpg = KeyPairGenerator.getInstance(
        KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
kpg.initialize(new KeyGenParameterSpec.Builder(
        "mykey", KeyProperties.PURPOSE_SIGN)
        .setDigests(KeyProperties.DIGEST_SHA256)
        .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PSS)
        .build());

需要设置摘要和填充模式的其他选项是必需的。这是因为遵循良好的加密安全实践,AndroidKeyStore现在限制了密钥可以使用的方式(签名 vs 解密、摘要和填充模式等)到一个指定的集合中。如果您尝试以未在创建密钥时指定的方式使用密钥,则将失败。如果您的设备有安全硬件,此错误实际上是由安全硬件强制执行的,因此即使攻击者获取了设备的root权限,密钥仍然只能按定义的方式使用。

KeyGenParameterSpec还支持创建ECDSA、AES和HMAC密钥,并允许您对密钥的使用方式进行其他限制。例如,如果您使用setUserAuthenticationRequired方法,除非用户在场以认证自己,否则无法使用该密钥。


4
如果您的目标是早期版本的 Android,该怎么办? - filthy_wizard
@Oximer 在 KeyGenParameterSpec Javadoc 中有示例。 - divegeek
1
@filthy_wizard如果你要针对较低的SDK级别,则必须使用KeyPairGeneratorSpec。 - divegeek

2

从SDK 1823 = KeyPairGeneratorSpec

SDK 23及以上版本 = KeyGenParameterSpec

@RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
            fun setAlgorithmParameterSpec(context: Context?) {
                val start = GregorianCalendar();
                val end = GregorianCalendar();
                end.add(Calendar.YEAR, 10);
                val spec: AlgorithmParameterSpec?
                if (Build.VERSION.SDK_INT < 23) {
                    spec = context?.let {
                        android.security.KeyPairGeneratorSpec.Builder(it)
                            // Alias - is a key for your KeyPair, to obtain it from Keystore in future.
                            .setAlias(alias ?: "")
                            // The subject used for the self-signed certificate of the generated pair
                            .setSubject(X500Principal("CN=$alias"))
                            // The serial number used for the self-signed certificate of the generated pair.
                            .setSerialNumber(BigInteger.valueOf(1337))
                            // Date range of validity for the generated pair.
                            .setStartDate(start.time).setEndDate(end.time)
                            .build()
                    };
                } else {
                    spec = KeyGenParameterSpec.Builder(alias ?: "", KeyProperties.PURPOSE_DECRYPT)
                        .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
                        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
                        .build();
                }
            }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接