You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

API 23下KeyGenerator初始化崩溃问题求助

问题分析与解决

你遇到的崩溃根源是未指定KeyGenerator使用AndroidKeyStore提供器。API23虽已引入KeyGenParameterSpec,但默认获取的KeyGenerator实例来自BouncyCastle,该实现并不支持用KeyGenParameterSpec初始化密钥生成器,因此抛出"Not Implemented"异常。

修复代码

修改密钥生成逻辑,在获取KeyGenerator时明确指定AndroidKeyStore提供器即可解决问题:

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()
}

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"
}

额外说明

  • API23开始AndroidKeyStore正式支持AES-256密钥,但需确保设备密钥库支持该长度(多数现代设备均兼容)。
  • 若不指定提供器,系统会选用默认的BouncyCastle实现,它与AndroidKeyStore的参数规范不兼容,这是崩溃的核心原因。

内容的提问来源于stack exchange,提问作者Saul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 10:30:49