Skip to content

Instantly share code, notes, and snippets.

@MaaxGr
Created July 11, 2022 06:17
Show Gist options
  • Save MaaxGr/2ccd4de705716e99e55dd6fe566542ab to your computer and use it in GitHub Desktop.
Save MaaxGr/2ccd4de705716e99e55dd6fe566542ab to your computer and use it in GitHub Desktop.
AES Encryption with Kotlin
interface AESEncryption {
fun setKey(myKey: String)
fun encrypt(strToEncrypt: String): String
fun decrypt(strToDecrypt: String): String
}
class AESEncryptionImpl: AESEncryption {
private var secretKey: SecretKeySpec? = null
override fun setKey(myKey: String) {
try {
var key = myKey.toByteArray(charset("UTF-8"))
val sha = MessageDigest.getInstance("SHA-1")
key = sha.digest(key)
key = key.copyOf(16)
secretKey = SecretKeySpec(key, "AES")
} catch (e: NoSuchAlgorithmException) {
e.printStackTrace()
} catch (e: UnsupportedEncodingException) {
e.printStackTrace()
}
}
override fun encrypt(strToEncrypt: String): String {
val cipher: Cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
cipher.init(Cipher.ENCRYPT_MODE, secretKey)
return Base64.getEncoder()
.encodeToString(cipher.doFinal(strToEncrypt.toByteArray(charset("UTF-8"))))
}
override fun decrypt(strToDecrypt: String): String {
val cipher: Cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING")
cipher.init(Cipher.DECRYPT_MODE, secretKey)
return String(
cipher.doFinal(
Base64.getDecoder()
.decode(strToDecrypt)
)
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment