Skip to content

Instantly share code, notes, and snippets.

@DuckSoft
Created October 5, 2018 22:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DuckSoft/f0f6c7b3d4bc949faf12e2184ccaaeff to your computer and use it in GitHub Desktop.
Save DuckSoft/f0f6c7b3d4bc949faf12e2184ccaaeff to your computer and use it in GitHub Desktop.
Kotlin MD5 Snipplet

Code

@Suppress("SpellCheckingInspection")
fun ByteArray.toHexStringLCase(): String = "0123456789abcdef".let { hexChars ->
    StringBuilder(this.size * 2).also { s ->
        this.forEach { byte ->
            byte.toInt().also { int ->
                s.append(hexChars[int shr 4 and 0x0f])
                s.append(hexChars[int and 0x0f])
            }
        }
    }.toString()
}

fun String.toMD532Bytes() = MessageDigest.getInstance("MD5")!!.digest(this.toByteArray())!!
fun String.toMD532String() = toMD532Bytes().toHexStringLCase()

Test

import io.kotlintest.shouldBe
import io.kotlintest.specs.StringSpec

class EncryptionExtensionKtTest : StringSpec({
    "32-bit lower-case MD5 test" {
        "".toMD532String() shouldBe "d41d8cd98f00b204e9800998ecf8427e"
        "123456".toMD532String() shouldBe "e10adc3949ba59abbe56e057f20f883e"
    }
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment