How do I pass a string to a function requiring BYTE*?

151 Views Asked by At

I've copied the entirety of this code: https://learn.microsoft.com/en-us/windows/win32/seccrypto/example-c-program--creating-an-hmac

I turned it into a function that accepts two strings. I would like these strings to be in place of Data1 and Data2.

BYTE        Data1[]     = {0x70,0x61,0x73,0x73,0x77,0x6F,0x72,0x64};
BYTE        Data2[]     = {0x6D,0x65,0x73,0x73,0x61,0x67,0x65};

I've tried everything I've found online up until this point and the function does not print the same hash. How do I use strings to replace these values? More relevant code below.

if (!CryptHashData(
    hHash,                    // handle of the hash object
    Data1,                    // password to hash
    sizeof(Data1),            // number of bytes of data to add
    0))                       // flags
{
   printf("Error in CryptHashData 0x%08x \n", 
          GetLastError());
   goto ErrorExit;
}

...

if (!CryptHashData(
    hHmacHash,                // handle of the HMAC hash object
    Data2,                    // message to hash
    sizeof(Data2),            // number of bytes of data to add
    0))                       // flags
{
   printf("Error in CryptHashData 0x%08x \n", 
          GetLastError());
   goto ErrorExit;
}
1

There are 1 best solutions below

0
john On BEST ANSWER

The data and size methods of std::string can be used to get a pointer to and size of the char array managed by the string.

These methods can be used to pass the string data to a C function that is expecting pointer and size of data parameters.

Using the example above this would look something like this

string str = ...;
if (!CryptHashData(
    hHash,                    // handle of the hash object
    (BYTE*)str.data(),                    // password to hash
    str.size(),            // number of bytes of data to add
    0))

Note that data returns char*, in this case a cast is necessary to convert the pointer to BYTE*. Also note that size returns the array length in characters not bytes, but for a std::string these are the same.