Here am going to explain how we can generate RSA KeyPair (PrivateKey and PublicKey) from AndroidKeyStore also how we can get retrieve these keys from the AndroidkeyStore.
Here I am having an object file SecureStore.kt, where I am going to show you how we can generate RSA KeyPair (PrivateKey and PublicKey) also How we can read PrivateKey from the AndroidKeyStore.
Generate RSA KeyPair
fun generateDeviceKeyPair(): KeyPair {
val keyGen = KeyPairGenerator.getInstance("RSA", provider)
keyGen.initialize(
KeyGenParameterSpec.Builder(
DEVICE_KEYPAIR_ALIAS,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
.setKeySize(4096)
.build()
)
return keyGen.generateKeyPair()
}
The above function generateDeviceKeyPair() will generate a new RSA KeyPair from AndroidKeyStore with a KeySize 4096.
Getting PrivateKey from AndroidKeyStore
fun getDevicePrivateKey() : PrivateKey?{
if(androidKs.containsAlias(DEVICE_KEYPAIR_ALIAS))
return androidKs.getKey(DEVICE_KEYPAIR_ALIAS, null) as PrivateKey
return null
}
The above function getDevicePrivateKey() will return the PrivateKey of the RSA KeyPair which we created before
Final Code
package com.b-mates.utils
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import java.security.KeyPair
import java.security.KeyPairGenerator
import java.security.KeyStore
import java.security.PrivateKey
object SecureStore {
private const val provider = "AndroidKeyStore"
private const val DEVICE_KEYPAIR_ALIAS = "DEVICE_KEYPAIR_ALIAS"
val androidKs = KeyStore.getInstance(provider).apply { load(null) }
fun generateDeviceKeyPair(): KeyPair {
val keyGen = KeyPairGenerator.getInstance("RSA", provider)
keyGen.initialize(
KeyGenParameterSpec.Builder(
DEVICE_KEYPAIR_ALIAS,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
.setKeySize(4096)
.build()
)
return keyGen.generateKeyPair()
}
fun getDevicePrivateKey() : PrivateKey?{
if(androidKs.containsAlias(DEVICE_KEYPAIR_ALIAS))
return androidKs.getKey(DEVICE_KEYPAIR_ALIAS, null) as PrivateKey
return null
}
}
No comments:
Post a Comment