我正在尝试使用 Keystore 创建一个加密/解密类,但它在 API 23 上崩溃。我知道这是应该开始支持它的 Api。
抛出异常:
java.security.InvalidAlgorithmParameterException: Not Implemented
at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseKeyGenerator.engineInit(BaseKeyGenerator.java:40)
这就是我生成密钥的方式。
private fun generateSecretKey(): SecretKey {
return KeyGenerator.getInstance(ALGORITHM).apply {
init(
KeyGenParameterSpec.Builder(
ALIAS,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
)
.setKeySize(256) // key size in bits
.setBlockModes(BLOCK_MODE)
.setEncryptionPaddings(PADDING)
.build()
)
}.generateKey()
}
companion object {
private const val ALIAS = "secret_key"
private const val ALGORITHM = KeyProperties.KEY_ALGORITHM_AES
private const val BLOCK_MODE = KeyProperties.BLOCK_MODE_CBC
private const val PADDING = KeyProperties.ENCRYPTION_PADDING_PKCS7
private const val TRANSFORMATION = "$ALGORITHM/$BLOCK_MODE/$PADDING"
}
这里有人遇到过这种情况,可以告诉我我做错了什么吗?
您必须在
getInstance
调用中指定提供商。
试试这个
private fun generateSecretKey(): SecretKey {
return KeyGenerator.getInstance(ALGORITHM, "AndroidKeyStore").apply {
init(
KeyGenParameterSpec.Builder(
ALIAS,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
)
.setKeySize(256) // key size in bits
.setBlockModes(BLOCK_MODE)
.setEncryptionPaddings(PADDING)
.build()
)
}.generateKey()
}