CryptAcquireContext and CryptReleaseContext example

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");
	}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s