Created
January 12, 2021 21:40
-
-
Save DjangoLC/f3a7b4751387d7078a6dfc6ce055d37b to your computer and use it in GitHub Desktop.
Aes Util fo rencrypt to aes 256
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
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