Skip to content

Instantly share code, notes, and snippets.

@qamarelsafadi
Created June 16, 2023 12:23
Show Gist options
  • Save qamarelsafadi/b39b61bcd91b6d5ad580888a77ef60d8 to your computer and use it in GitHub Desktop.
Save qamarelsafadi/b39b61bcd91b6d5ad580888a77ef60d8 to your computer and use it in GitHub Desktop.
class Encryptor {
lateinit var encryption: ByteArray
private set
lateinit var iv: ByteArray
private set
@Throws(
UnrecoverableEntryException::class,
NoSuchAlgorithmException::class,
KeyStoreException::class,
NoSuchProviderException::class,
NoSuchPaddingException::class,
InvalidKeyException::class,
IOException::class,
InvalidAlgorithmParameterException::class,
SignatureException::class,
BadPaddingException::class,
IllegalBlockSizeException::class
)
fun encryptText(alias: String, textToEncrypt: String): ByteArray {
val cipher: Cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(alias))
iv = cipher.getIV()
return cipher.doFinal(textToEncrypt.toByteArray(charset("UTF-8"))).also {
encryption = it
}
}
@Throws(
NoSuchAlgorithmException::class,
NoSuchProviderException::class,
InvalidAlgorithmParameterException::class
)
private fun getSecretKey(alias: String): SecretKey {
val keyGenerator: KeyGenerator = KeyGenerator
.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEY_STORE)
keyGenerator.init(
KeyGenParameterSpec.Builder(
alias,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.build()
)
return keyGenerator.generateKey()
}
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