Last active
March 25, 2019 10:56
-
-
Save reuniware/3ca0be62e9dbdb3ff2766aa6912b345d to your computer and use it in GitHub Desktop.
Android kotlin encrypt decrypt example
This file contains hidden or 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
lateinit var secretKey : SecretKey | |
lateinit var iv : ByteArray | |
fun encrypt(context:Context, strToEncrypt: String): ByteArray { | |
val plainText = strToEncrypt.toByteArray(Charsets.UTF_8) | |
val keygen = KeyGenerator.getInstance("AES") | |
keygen.init(256) | |
val key = keygen.generateKey() | |
secretKey = key | |
val cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING") | |
cipher.init(Cipher.ENCRYPT_MODE, key) | |
val cipherText = cipher.doFinal(plainText) | |
iv = cipher.iv | |
val sb = StringBuilder() | |
for (b in cipherText) { | |
sb.append(b.toChar()) | |
} | |
Toast.makeText(context, "dbg encrypted = [" + sb.toString() + "]", Toast.LENGTH_LONG).show() | |
return cipherText | |
} | |
fun decrypt(context:Context, dataToDecrypt: ByteArray): ByteArray { | |
val cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING") | |
val ivSpec = IvParameterSpec(iv) | |
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec) | |
val cipherText = cipher.doFinal(dataToDecrypt) | |
val sb = StringBuilder() | |
for (b in cipherText) { | |
sb.append(b.toChar()) | |
} | |
Toast.makeText(context, "dbg decrypted = [" + sb.toString() + "]", Toast.LENGTH_LONG).show() | |
return cipherText | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment