Keypair RSA android


what is the best practice to create only one keypair for RSA encryption in all the android app cycle ?
I want to create the public key and the private key only once then use it whenever i want.


Yes you should create it one time with your alias key and next time before create new keystore object first you should check the same alias is already exist in keystore or not. If the alias is not exist in keystore then you should create new object. You can also check with the below code.

   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")
    } catch (ex: Exception) {

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(
            KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT

Answered By – Dharmender Manral

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published