Skip to content

Instantly share code, notes, and snippets.

@DjangoLC
Created January 12, 2021 21:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DjangoLC/f3a7b4751387d7078a6dfc6ce055d37b to your computer and use it in GitHub Desktop.
Save DjangoLC/f3a7b4751387d7078a6dfc6ce055d37b to your computer and use it in GitHub Desktop.
Aes Util fo rencrypt to aes 256
object Aes256 {
private fun cipher(operationMode: Int, secretKey: String = BuildConfig.KEY_ENCRYPT): Cipher {
if (secretKey.length != 32) throw RuntimeException("SecretKey length is not 32 chars")
val c = Cipher.getInstance("AES/CBC/PKCS5Padding")
val sk = SecretKeySpec(secretKey.toByteArray(Charsets.UTF_8), "AES")
val iv = IvParameterSpec(secretKey.substring(0, 16).toByteArray(Charsets.UTF_8))
c.init(operationMode, sk, iv)
return c
}
fun encrypt(str: String, secretKey: String = BuildConfig.KEY_ENCRYPT): String {
val encrypted =
cipher(Cipher.ENCRYPT_MODE, secretKey).doFinal(str.toByteArray(Charsets.UTF_8))
return String(Base64.encode(encrypted, Base64.DEFAULT))
}
fun decrypt(str: String, secretKey: String = BuildConfig.KEY_ENCRYPT): String {
val byteStr = Base64.decode(str.toByteArray(Charsets.UTF_8), Base64.DEFAULT)
return String(cipher(Cipher.DECRYPT_MODE, secretKey).doFinal(byteStr))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment