Search code examples
nim-lang

MD5 on an array, array[0..63, uint8] to cstring conversion


I'm trying to perform a md5Update on an array[0..63, uint8] but I'm getting

Error: type mismatch: got (MD5Context, array[0..63, uint8], int)
but expected one of: 
md5.md5Update(c: var MD5Context, input: cstring, len: int)

It seems it wants a ctring input and not a buffer. How then can I perform an md5Update() on binary data? (I don't want a null character at the end...)


Solution

  • You can cast your buffer to a cstring with cast[cstring](addr myBuf). Note that you also have to pass a var MD5Context, which means it has to be mutable (defined inside a var or passed as a var parameter). Code example:

    const arr = [0'u8, 0, 0]
    var ctx: MD5Context
    md5Init(ctx)
    md5Update(ctx, cast[cstring](unsafeAddr arr), sizeof(arr))
    var digest: MD5Digest
    md5Final(ctx, digest)