KeyPairGeneratorSpec 在API 23中已经被弃用。您该如何处理这个警告?
示例代码:
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
kpg.initialize(new KeyPairGeneratorSpec.Builder(context).build());
KeyPairGeneratorSpec 在API 23中已经被弃用。您该如何处理这个警告?
示例代码:
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
kpg.initialize(new KeyPairGeneratorSpec.Builder(context).build());
根据文档,你应该使用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
方法,除非用户在场以认证自己,否则无法使用该密钥。
从SDK 18到23 = 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();
}
}