0

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.

Deividas
  • 39
  • 1
  • 13
  • 2
    You are not supposed to call `CryptGenKey` with a `NULL` handle. Period. You write `result = ...`, well use `result` and take appropriate action if it is `false`. – Jabberwocky May 19 '17 at 14:36
  • I guess you meant CryptDestroyKey. I do understand how this should be handled, and it's already implemented but why not handle it like in an older version? It's a breaking change that would occur in the run-time and Microsoft did not document it? – Deividas May 19 '17 at 14:39
  • Yes, I meant `CryptDestroyKey`. Did Microsoft document that a NULL pointer could be passed to these functions? You were probably just running into undefined behaviour. – Jabberwocky May 19 '17 at 14:48

0 Answers0