Use Facebook Conceal To Encrypt And Decrypt String (Kotlin)

April 14, 2018

Setup Facebook Conceal.

Encrypt string

var encryptedData = crypto.encrypt(value.toByteArray(Charsets.UTF_8), Entity.create("Test"))
encryptedData = Base64.encodeToString(encryptedData, Base64.DEFAULT)

Decrypt string

var value = crypto.decrypt(Base64.decode(encryptedData, Base64.DEFAULT), Entity.create("Test"))
value.toString(Charsets.UTF_8)

You can write an Kotlin Extentions to encrypt and decrypt string using Facebook Conceal.

fun Crypto.encrypt(key: String, value: String): String {
    val data = encrypt(value.toByteArray(Charsets.UTF_8), Entity.create(key))
    return Base64.encodeToString(data, Base64.DEFAULT)
}

fun Crypto.decrypt(key: String, value: String): String {
    val data = decrypt(Base64.decode(value, Base64.DEFAULT), Entity.create(key))
    return data.toString(Charsets.UTF_8)
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.