Created
June 16, 2023 12:25
-
-
Save qamarelsafadi/b5b474e046c0200464090d5c50f52547 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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