Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
4.00/5 (1 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:

C++
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

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:
C++
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);
 
Share this answer
 
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, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900