Skip to content

Instantly share code, notes, and snippets.

@shakir915
Created December 5, 2023 05:16
Show Gist options
  • Save shakir915/d3eafeda0825a1e15957b60a02bd12e7 to your computer and use it in GitHub Desktop.
Save shakir915/d3eafeda0825a1e15957b60a02bd12e7 to your computer and use it in GitHub Desktop.
aes Encrypt Decrypt
@file:OptIn(ExperimentalEncodingApi::class)
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
import kotlin.io.encoding.Base64
import kotlin.io.encoding.ExperimentalEncodingApi
@OptIn(ExperimentalEncodingApi::class)
fun decrptAES(cipherText: String?): String {
try {
val keySpec = SecretKeySpec("yeygxvhdnndnndnn".toByteArray(), "AES")
var cipher: Cipher? = null
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
cipher.init(Cipher.DECRYPT_MODE, keySpec)
val decode: ByteArray = Base64.decode(cipherText!!.toByteArray())
val decryptedText = cipher.doFinal(decode)
return String(decryptedText)
} catch (e: Exception) {
return cipherText ?: ""
}
}
@OptIn(ExperimentalEncodingApi::class)
fun encryptAES(cipherText: String?): String {
try {
val keySpec = SecretKeySpec("yeygxvhdnndnndnn".toByteArray(), "AES")
var cipher: Cipher? = null
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
cipher?.init(Cipher.ENCRYPT_MODE, keySpec)
val ba = cipher!!.doFinal(cipherText!!.toByteArray())
val decode: ByteArray = Base64.encodeToByteArray(ba)
return String(decode)
} catch (e: Exception) {
return cipherText ?: ""
}
}
println(encryptAES("ABCD"))
println(decrptAES("eCZPlzXj5m0wtMBKy+U6Zg=="))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment