Can anybody help me with this? I need to compute a...
# kotlin-native
m
Can anybody help me with this? I need to compute a hex SHA-256 checksum of a ByteArray on iOS. This should be simple because the OS already provides this functionality but I failed to convert some code which I found on the internet to Kotlin via C interop. The code I already have is inside the thread.
Copy code
@OptIn(ExperimentalForeignApi::class)
actual fun hexChecksum(byteArray: ByteArray): String {
    require(algorithm == "SHA-256")

    val data = byteArray.toData()
    
    /*
        uint8_t digest[CC_SHA256_DIGEST_LENGTH];

        CC_SHA256(data.bytes, data.length, digest);

        NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];

        for(int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
            [output appendFormat:@"%02x", digest[i]];
        }

        return output; // convert to Kotlin String
    */

}

@OptIn(ExperimentalForeignApi::class, BetaInteropApi::class)
internal inline fun ByteArray.toData(offset: Int = 0): NSData {
    if (isEmpty()) return NSData()
    val pinned = pin()
    return NSData.create(
        bytesNoCopy = pinned.addressOf(offset),
        length = size.toULong(),
        deallocator = { _, _ -> pinned.unpin() }
    )
}
t
I know this may not be the answer you are looking for, but I too had some custom code for this but it did not work perfectly in all cases. Then I found this mp lib and all is better in the world: https://github.com/KotlinCrypto/MACs
🙏 1
👍 1
m
Any working solution is a good solution 😉. Thanks a lot. It worked for me in iOS but I couldn’t get it working in the common code. But iOS was actually what I was looking for.
t
Understood. As a bonus, this lib works in other targets too, so you may be future proof in that regard. 🙂 (I hope to get my common working in wasm one day, and this makes it easier).
FYI, this is the code I ended up with this lib:
Copy code
fun Platform.signSha256(value: String, key: String): String {
    return HmacSHA256(key.toByteArray()).doFinal(value.toByteArray()).encodeBase64()
}
nice and clean and simple