Android: String to MD5

April 8, 2019
fun String.toMD5(): String {
    // toByteArray: default is Charsets.UTF_8 - https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/to-byte-array.html
    val bytes = MessageDigest.getInstance("MD5").digest(this.toByteArray())
    return bytes.toHex()
}

fun ByteArray.toHex(): String {
    return joinToString("") { "%02x".format(it) }
}
val hash = "abc".toMD5() // "900150983cd24fb0d6963f7d28e17f72"

NOTE: MD5 Test Suite

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.