I am working on a task in a C++ project to upgrade some components from building with VS2010 to build with VS2015 and noticed a strange behavior that I could not find any discussions online. Simplified code is as follows:
#include "stdafx.h"
int main()
{
HCRYPTPROV hCryptProv = NULL;
LPCTSTR UserName = L"MyKeyContainer";
HCRYPTKEY hKey = NULL;
bool result = CryptAcquireContext(&hCryptProv, UserName, NULL, PROV_RSA_FULL, 0);
result = CryptGenKey(hCryptProv, CALG_RC4, 25 << 16, &hKey); // this line is meant to produce an invalid hKey.
result = CryptDestroyKey(hKey);
result = CryptReleaseContext(hCryptProv, 0);
return 0;
}
and precompiled header:
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#include <Wincrypt.h>
If I try to build and run this code snippet with VS2010, CryptGenKey returns a false result and hKey value of 0. Passing hKey to the CryptDestroyKey returns false, but does not throw an exception.
If I try to build and run this code snippet with VS2015, CryptGenKey returns a false result and hKey value of 0. Passing hKey to the CryptDestroyKey throws an access violation exception.
Could someone explain the reason behind this implementation and why Windows won't handle 0 in the more up to date VS version? This could be a potential problem for other projects if they do not manage the 0 themselves.