kotlinhashcryptographymd5sha

How to Generate an MD5 hash in Kotlin?


Generate MD5 hash of a string using standard library in Kotlin?

I have tried below mention code

import java.math.BigInteger
import java.security.MessageDigest

fun md5(input:String): String {
    val md = MessageDigest.getInstance("MD5")
    return BigInteger(1, md.digest(input.toByteArray())).toString(16).padStart(32, '0')
}

Is this the best way or which?


Solution

  • Using java.security.MessageDigest is the simplest way

    import java.math.BigInteger
    import java.security.MessageDigest
    
    fun md5(input:String): String {
        val md = MessageDigest.getInstance("MD5")
        return BigInteger(1, md.digest(input.toByteArray())).toString(16).padStart(32, '0')
    }