Click here to Skip to main content
14,544,301 members
Rate this:
Please Sign up or sign in to vote.
See more:
I am trying to encapsulate CryptStringToBinary in a function of my own but I am not having any luck returning the pointer.
In the code below the pointer lpDecoded is zero.

What I have tried:

DWORD Base64Decode(LPCSTR pszEncoded, LPBYTE lpDecode64) {
	DWORD dwBufLen = 0;

	// determine size of the encoded buffer
	CryptStringToBinary(pszEncoded, 0,
		CRYPT_STRING_BASE64, NULL, &dwBufLen, NULL, NULL);

	// allocate decoded buffer
	lpDecode64 = (LPBYTE)malloc(dwBufLen);
	memset(lpDecode64, 0x00, dwBufLen);

	// decode the Base64 string
	CryptStringToBinary(pszEncoded, 0,
		CRYPT_STRING_BASE64, lpDecode64,
		&dwBufLen, NULL, NULL);

	return dwBufLen;
}

	CHAR *lpString64 = 0;
	LPBYTE lpDecoded = 0;
	DWORD dwDecodeLen = 0;

	// decode the Base64 string
	dwDecodeLen = Base64Decode(lpString64, lpDecoded);
Posted
Updated 18-Jun-19 10:13am

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

You need to pass the address of the pointer into the function. The parameter lpDecoded is a temporary one inside the function, so any change to it will disappear when the function returns. Change your code to the following so the buffer address is put in the original pointer:
DWORD Base64Decode(LPCSTR pszEncoded, LPBYTE* lpDecode64) {
	DWORD dwBufLen = 0;

	// determine size of the encoded buffer
	CryptStringToBinary(pszEncoded, 0,
		CRYPT_STRING_BASE64, NULL, &dwBufLen, NULL, NULL);

	// allocate decoded buffer
	*lpDecode64 = (LPBYTE)malloc(dwBufLen);
	memset(*lpDecode64, 0x00, dwBufLen); // this is redundant as CryptStringToBinary will immediately overwrite it

	// decode the Base64 string
	CryptStringToBinary(pszEncoded, 0,
		CRYPT_STRING_BASE64, *lpDecode64,
		&dwBufLen, NULL, NULL);

	return dwBufLen;
}

	CHAR *lpString64 = 0;
	LPBYTE lpDecoded = 0;
	DWORD dwDecodeLen = 0;

	// decode the Base64 string
	dwDecodeLen = Base64Decode(lpString64, &lpDecoded);
   
Comments
Roland M Smith 18-Jun-19 16:30pm
   
That worked, thanks!
Richard MacCutchan 18-Jun-19 17:49pm
   
One of C's many traps for the unwary.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100