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) }}
@RunWith(AndroidJUnit4::class)class MD5Test { @Test fun test() { // echo -n a | md5sum // https://tools.ietf.org/html/rfc1321 val testSets = mapOf( "" to "d41d8cd98f00b204e9800998ecf8427e", "a" to "0cc175b9c0f1b6a831c399e269772661", "abc" to "900150983cd24fb0d6963f7d28e17f72", "message digest" to "f96b697d7cb7938d525a2f31aaf161d0", "abcdefghijklmnopqrstuvwxyz" to "c3fcd3d76192e4007dfb496cca67e13b", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" to "d174ab98d277d9f5a5611c2c9f419d9f", "12345678901234567890123456789012345678901234567890123456789012345678901234567890" to "57edf4a22be3c955ac49da2e2107b67a", "你好吗?" to "bb0b6bc45375143826f72439e050743e", "お元気ですか" to "2e0bd9e58d042f5234a1202cc3c7d499" ) for ((key, value) in testSets) { assertThat(key.toMD5(), `is`(value)) } }}
NOTE: Refer Get MD5 of String using Linux Command Line.
References: