Skip to content

Instantly share code, notes, and snippets.

@reuniware
Last active March 25, 2019 10:56
Show Gist options
  • Save reuniware/3ca0be62e9dbdb3ff2766aa6912b345d to your computer and use it in GitHub Desktop.
Save reuniware/3ca0be62e9dbdb3ff2766aa6912b345d to your computer and use it in GitHub Desktop.
Android kotlin encrypt decrypt example
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