Skip to content

Instantly share code, notes, and snippets.

@qamarelsafadi
Created June 16, 2023 12:25
Show Gist options
  • Save qamarelsafadi/b5b474e046c0200464090d5c50f52547 to your computer and use it in GitHub Desktop.
Save qamarelsafadi/b5b474e046c0200464090d5c50f52547 to your computer and use it in GitHub Desktop.
class Decryptor {
private var keyStore: KeyStore? = null
init {
initKeyStore()
}
@Throws(
KeyStoreException::class,
CertificateException::class,
NoSuchAlgorithmException::class,
IOException::class
)
private fun initKeyStore() {
keyStore = KeyStore.getInstance(ANDROID_KEY_STORE)
keyStore?.load(null)
}
@Throws(
UnrecoverableEntryException::class,
NoSuchAlgorithmException::class,
KeyStoreException::class,
NoSuchProviderException::class,
NoSuchPaddingException::class,
InvalidKeyException::class,
IOException::class,
BadPaddingException::class,
IllegalBlockSizeException::class,
InvalidAlgorithmParameterException::class
)
fun decryptData(alias: String, encryptedData: ByteArray?, encryptionIv: ByteArray?): String {
val cipher: Cipher = Cipher.getInstance(TRANSFORMATION)
val spec = GCMParameterSpec(128, encryptionIv)
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(alias), spec)
return String(cipher.doFinal(encryptedData))
}
@Throws(
NoSuchAlgorithmException::class,
UnrecoverableEntryException::class,
KeyStoreException::class
)
private fun getSecretKey(alias: String): SecretKey {
return (keyStore?.getEntry(alias, null) as KeyStore.SecretKeyEntry).getSecretKey()
}
companion object {
private const val TRANSFORMATION = "AES/GCM/NoPadding"
private const val ANDROID_KEY_STORE = "AndroidKeyStore"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment