views:

18

answers:

1

Hello everybody, does anyone know why this code is not working?

 #include "stdafx.h"
#include <windows.h>
#include <WinCrypt.h>


int _tmain(int argc, _TCHAR* argv[])
{
wchar_t *bin = TEXT("ProductID:1233===>55555");
BYTE out2[1000];
DWORD olen;
olen = 1000;

if (CryptStringToBinary(bin, 0, 1, out2, &olen, 0, 0) == 0)
{
    wprintf(TEXT("Failure\n"));
}
else
{
//wprintf(TEXT("rn%s\n"),out2);
    wprintf(TEXT("Success\n"));
}
system("pause");
    return 0;
}

Thank you very much in advance!

Tom

A: 

Because you specified a length (parameter 2) of 0?

Edit: Just to clarify our eventual solution in the comments below, the code in the original question (since edited) contained two errors:

  1. It was calling CryptBinaryToString instead of CryptStringToBinary. Since it's invalid to pass a 0 in the second parameter to CryptBinaryToString, the function was failing.
  2. It was passing 1 in the third parameter (dwFlags), which is interpreted as CRYPT_STRING_BASE64. Since the string to encrypt wasn't in base 64 (it contained invalid characters such as ':'), the function was failing. In general, passing a raw value instead of using an existing definition (e.g., CRYPT_STRING_BASE64) is not a good idea.
Emerick Rogul
If you specify 0 in the lenght parameter the string is considered a null terminated string... so it should work. This is actually what I'm trying to get working.
Tom Jones
Yes, but you're calling CryptBinaryToString. :-)
Emerick Rogul
You're absolutely right, thank you. I updated the code with CryptStringToBinary and it's not working still. Any ideas?
Tom Jones
This call works if I specify a normal string like 12345, but with this string that contains "=" and ">" characters doesn't work... I need this characters in the string, is there a way to make it work?
Tom Jones
Yeah, I updated the code.. I'm indeed using CryptStringToBinary :)
Tom Jones
It doesn't accept = and > because you passed 1 (CRYPT_STRING_BASE64) for parameter 3 and those aren't legal characters for base 64. It seems like you want to pass CRYPT_STRING_BINARY, but you should probably review the documentation for that function and see which flag makes the most sense for you: http://msdn.microsoft.com/en-us/library/aa380285(VS.85).aspx
Emerick Rogul
The key here is the documentation, which states that this function converts a *formatted* string; your string just happens not to match the format you specified.
Emerick Rogul
Thanks my friend
Tom Jones
Glad we figured it out... :-)
Emerick Rogul