Issue
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.
Solution
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")
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()
}
}
}
}
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