Search code examples
c++cdebuggingwinapicng

Convert HEX to printable string/char


I'm using CNG to generate a hash. Result of BCryptFinishHash call is MD5 of a input in hex form. Example:

char *outHash = "\x02\x34\x75\01..."

I want to convert it to printable string: 02347501...

How can I do that?


Solution

  • we can use CryptBinaryToString here with CRYPT_STRING_HEXASCII or CRYPT_STRING_HEX or CRYPT_STRING_HEXRAW or CRYPT_STRING_HEX | CRYPT_STRING_NOCRLF or CRYPT_STRING_HEXRAW | CRYPT_STRING_NOCRLF depen how you want format string. for example

    void print(PUCHAR pbHash, ULONG cbHash, DWORD dwFlags = CRYPT_STRING_HEXRAW | CRYPT_STRING_NOCRLF)
    {
        ULONG cch = 0;
        if (CryptBinaryToStringW(pbHash, cbHash, dwFlags, 0, &cch))
        {
            if (PWSTR sz = (PWSTR)_malloca(cch * sizeof(WCHAR)))
            {
                if (CryptBinaryToStringW(pbHash, cbHash, dwFlags, sz, &cch))
                {
                    DbgPrint("%S\n", sz);
                }
                _freea(sz);
            }
        }
    }