Hello guys, I need your help I'm building kmm appl...
# multiplatform
m
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
thank you, I will check this
e
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
perfect, I need it in hex string
j
MIGHT consider Okio’s ByteString, which implements md5 and hex in multiplatform code
m
Thank you, I will check this
334 Views