CryptAcquireContext and CryptReleaseContext example
#include <windows.h>
#include <string>
#include <winbase.h>
#include <iostream>
using namespace std;
#include <Wincrypt.h >
void main()
{
LPCSTR rgwchKeyContName = "Test123456";
HCRYPTPROV m_hCryptoProviderFB;
BOOL ret;
BOOL ret2;
ret=CryptAcquireContext(&m_hCryptoProviderFB, rgwchKeyContName, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_SILENT);
if (!ret && GetLastError() == NTE_BAD_KEYSET)
{
printf("\nUnable to open Keyset.CryptAcquireContext failed with error: 0x%X . \nWe will try creating key",GetLastError());
ret2=CryptAcquireContext(&m_hCryptoProviderFB, rgwchKeyContName, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_NEWKEYSET | CRYPT_SILENT);
if (!ret2)
{
printf("\nCryptAcquireContext failed creating key.Error: 0x%X",GetLastError());
}
else
{
printf("\nKey created");
}
exit;
}
else if (!ret && GetLastError() == NTE_BAD_KEYSET)
{
printf("CryptAcquireContext failed with error: 0x%X",GetLastError());
}
else
{
printf("CryptAcquireContext opened key. Return value is 0x%X.",ret);
}
if (CryptReleaseContext(m_hCryptoProviderFB,0))
{
//printf("\nHandle has been released.\n");
}
else
{
printf("\nHandle could not be released.\n");
}
}