RSA 密钥对 android

Keypair RSA android

在所有 android 应用程序周期中只为 RSA 加密创建一个密钥对的最佳做法是什么? 我只想创建 public 密钥和私钥一次,然后随时使用它。

是的,您应该使用别名密钥创建一次,下次在创建新的密钥库对象之前,您应该首先检查密钥库中是否已经存在相同的别名。如果密钥库中不存在别名,那么您应该创建新对象。您也可以使用以下代码查看。

   class AndroidKeyStore {
companion object {
    private val CIPHER_TYPE = "RSA/ECB/PKCS1Padding"
    private val CIPHER_PROVIDER = "AndroidOpenSSL"
    private var keyStore: KeyStore? = null
    const val KEY_ALIAS = "Keyalaisasfd"
}

init {
    try {
        keyStore = KeyStore.getInstance("AndroidKeyStore")
        keyStore?.load(null)
        generateKey()
    } catch (ex: Exception) {
    }
}

@Throws(Exception::class)
private fun generateKey() {
// Create new key if needed
if (keyStore != null) {
    if (!keyStore!!.containsAlias(KEY_ALIAS)) {
        val kpg: KeyPairGenerator =
            KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore")
        val parameterSpec: KeyGenParameterSpec = KeyGenParameterSpec.Builder(
            KEY_ALIAS,
            KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
        )
            .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
            .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
            .build()
        kpg.initialize(parameterSpec)
        kpg.generateKeyPair()
    }
}
}
}