Skip to content

Instantly share code, notes, and snippets.

@Jaosrikate
Created January 25, 2022 17:04
Show Gist options
  • Save Jaosrikate/61d0697a007f82058790ca2a5b762612 to your computer and use it in GitHub Desktop.
Save Jaosrikate/61d0697a007f82058790ca2a5b762612 to your computer and use it in GitHub Desktop.
private fun getOrCreateSecretKey(keyName: String): SecretKey {
// If Secretkey was previously created for that keyName, then grab and return it.
try {
val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE)
try {
keyStore.load(null) // Keystore must be loaded before it can be accessed
keyStore.getKey(keyName, null)?.let {
return it as SecretKey
}
} catch (ex: Exception) {
when (ex) {
is CertificateException, is IOException, is NoSuchAlgorithmException -> {
Logger.e("CryptographyManager", ex.toString())
}
is UnrecoverableKeyException -> {
Logger.e("CryptographyManager", "User disable unlock screen")
}
else -> throw ex
}
}
} catch (e: KeyStoreException) {
throw e
}
// if you reach here, then a new SecretKey must be generated for that keyName
val paramsBuilder = KeyGenParameterSpec.Builder(
keyName,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
)
paramsBuilder.apply {
setBlockModes(ENCRYPTION_BLOCK_MODE)
setEncryptionPaddings(ENCRYPTION_PADDING)
setKeySize(KEY_SIZE)
setUserAuthenticationRequired(true)
setInvalidatedByBiometricEnrollment(true)
}
val keyGenParams = paramsBuilder.build()
try {
val keyGenerator = KeyGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_AES,
ANDROID_KEYSTORE
)
keyGenerator.init(keyGenParams)
return keyGenerator.generateKey()
} catch (e: Exception) {
throw e
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment