【发布时间】:2016-09-04 07:57:01
【问题描述】:
我需要创建一个 android KeyPairGeneratorSpec 的实例,以前可以使用这个 builder 类,但它在 API 23 中已被弃用。那么,现在创建它的正确方法是什么?
一般来说,我需要创建一个带有密钥大小的KeyPairGeneratorSpec。现在怎么办?
【问题讨论】:
标签: android android-keystore key-pair
我需要创建一个 android KeyPairGeneratorSpec 的实例,以前可以使用这个 builder 类,但它在 API 23 中已被弃用。那么,现在创建它的正确方法是什么?
一般来说,我需要创建一个带有密钥大小的KeyPairGeneratorSpec。现在怎么办?
【问题讨论】:
标签: android android-keystore key-pair
KeyPairGeneratorSpec 已被弃用,取而代之的是 KeyGenParameterSpec。
我不一定会因为 KeyPairGeneratorSpec 已弃用而转而使用 KeyGenParameterSpec,因为如果您想避免使用已弃用的类并保持向后兼容性,则必须为两者编写单独的代码路径同一时间。
下面是一些使用新的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);
}
}
【讨论】:
KeyPairGeneratorSpec 已被弃用,这意味着它在 Android 6.0+ 中不可用?
deprecated 并不意味着它不可用 - 只是you're recommended not to use it 因为他们希望您使用另一种(更好的)方法。他们可能会在未来的版本中删除它,但deprecated 只是一个提示,试图引导开发人员停止使用它。如果遵循最佳实践,那么您应该尝试停止使用 deprecated 类,否则您可能会在将来更新您的目标 sdk 并发现它不再受支持。