https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
m

Mod

02/07/2023, 6:09 AM
Hello guys, I need your help I'm building kmm application and part of the api call is md5 hash key, I made the implementation for android part but for iOS I couldn't use CryptoKit because it's pure swift and using the CoreCrypto I faced a lot of trouble converting the swift code to kotlin this is the contract:
Copy code
expect object EncryptionHelper {
    fun md5(input: String): String
}
this is the Android part:
Copy code
import java.math.BigInteger
import java.security.MessageDigest

actual object EncryptionHelper {
    actual fun md5(input: String): String {
        val md = MessageDigest.getInstance("MD5")
        return BigInteger(1, md.digest(input.toByteArray())).toString(16).padStart(32, '0')
    }
}
in fact there is an example in this slack, https://kotlinlang.slack.com/archives/C3SGXARS6/p1544768698174600?thread_ts=1541771174.265700&cid=C3SGXARS6 (although
.toString(16)
looks suspiciously wrong to me… you'd need to
.padStart(2, '0')
or change how the string representation is generated)
replacing
CC_SHA256
with
CC_MD5
of course, but it works the same way
m

Mod

02/07/2023, 6:36 AM
thank you, I will check this
e

ephemient

02/07/2023, 6:39 AM
I'd probably do
Copy code
fun UByteArray.toHexString(): String = buildString(size * 2) {
    for (ubyte in this@toHexString) {
        append((ubyte.toInt() shr 4 and 15).digitToChar(radix = 16))
        append((ubyte.toInt() and 15).digitToChar(radix = 16))
    }
}
m

Mod

02/07/2023, 6:41 AM
perfect, I need it in hex string
j

jessewilson

02/07/2023, 12:42 PM
MIGHT consider Okio’s ByteString, which implements md5 and hex in multiplatform code
m

Mod

02/09/2023, 6:38 AM
Thank you, I will check this
205 Views