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

Android中RSA的KeyPairGenerator冻结UI及ECC替代方案咨询

Android RSA密钥生成冻结UI问题及ECC替代方案求助

我的问题和某一未解决问题重复,目前使用RSA算法生成密钥对用于非对称加密(公钥加密、生物识别解密),但密钥生成过程会冻结UI数秒,进度条也随之卡住。我尝试将生成代码放到后台线程,UI仍会冻结,找不到问题根源。考虑过更换加密算法,但官方文档未提及RSA存在这类问题,也不知道如何按照建议改用ECC算法重写代码及加密逻辑。

以下是密钥对生成代码:

keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM, ANDROID_KEYSTORE)

private fun createKeyPair() {
        keyPairGenerator.initialize(
            KeyGenParameterSpec.Builder(KEY_ALIAS, KeyProperties.PURPOSE_DECRYPT)
                .setKeySize(4096)
                .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP)
                .build()
        )
        keyPairGenerator.generateKeyPair()
    }

加密代码如下:

private const val ALGORITHM = "RSA"

private var cipher = Cipher.getInstance(TRANSFORMATION)

private fun initCipherForEncrypt() {
        if (!keyStoreInstance.containsAlias(KEY_ALIAS)) {
            keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM, ANDROID_KEYSTORE)
            createKeyPair()
        }

        val key: PublicKey = keyStoreInstance.getCertificate(KEY_ALIAS).publicKey
        val unrestricted: PublicKey = KeyFactory.getInstance(key.algorithm).generatePublic(X509EncodedKeySpec(key.encoded))
        val spec = OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec("SHA-1"), PSource.PSpecified.DEFAULT)
        cipher.init(Cipher.ENCRYPT_MODE, unrestricted, spec)
    }

fun encrypt(token: String): ByteArray {
        initCipherForEncrypt()
        return cipher.doFinal(token.toByteArray())
    }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 12:00:54