Android Keystore System
Android Keystore System
The Android Keystore system provides hardware-backed security for cryptographic keys, ensuring keys cannot be extracted from the device.
// Advanced Keystore implementation
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.security.keystore.UserNotAuthenticatedException
import java.security.KeyPairGenerator
import java.security.KeyStore
import java.security.PrivateKey
import java.security.Signature
class BiometricCryptoManager {
private val keyAlias = "BiometricKey"
fun generateBiometricKey() {
val keyPairGenerator = KeyPairGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_EC,
"AndroidKeyStore"
)
val spec = KeyGenParameterSpec.Builder(
keyAlias,
KeyProperties.PURPOSE_SIGN or KeyProperties.PURPOSE_VERIFY
)
.setAlgorithmParameterSpec(ECGenParameterSpec("secp256r1"))
.setDigests(KeyProperties.DIGEST_SHA256)
.setUserAuthenticationRequired(true)
.setUserAuthenticationValidityDurationSeconds(-1) // Require auth for every use
.build()
keyPairGenerator.initialize(spec)
keyPairGenerator.generateKeyPair()
}
fun signData(data: ByteArray): ByteArray? {
return try {
val keyStore = KeyStore.getInstance("AndroidKeyStore")
keyStore.load(null)
val privateKey = keyStore.getKey(keyAlias, null) as PrivateKey
val signature = Signature.getInstance("SHA256withECDSA")
signature.initSign(privateKey)
signature.update(data)
signature.sign()
} catch (e: UserNotAuthenticatedException) {
// User needs to authenticate with biometric
null
}
}
}