使用CryptoApi做PKCS#1格式加密

#include "stdafx.h"
#include 
#include 

#pragma comment(lib, "crypt32.lib")

int _tmain(int argc, _TCHAR* argv[])
{
	HCERTSTORE hStore = CertOpenSystemStore(NULL, L"MY");
	PCCERT_CONTEXT pCert = NULL;
	DWORD dwKeySpec = AT_KEYEXCHANGE;
	pCert = CertFindCertificateInStore(hStore, X509_ASN_ENCODING|PKCS_7_ASN_ENCODING, 0, CERT_FIND_KEY_SPEC, (void*)&dwKeySpec, NULL);
	if (pCert == NULL)
		return -1;
	HCRYPTPROV hCryptProv = NULL;
	BOOL bCallerFreeProvOrNCryptKey = FALSE;
	if (!CryptAcquireCertificatePrivateKey(pCert, 0, NULL, &hCryptProv, &dwKeySpec, &bCallerFreeProvOrNCryptKey))
	{
		return -1;
	}
	HCRYPTKEY hPrvKey = NULL;
	if (!CryptGetUserKey(hCryptProv, dwKeySpec, &hPrvKey))
		return -1;
	HCRYPTKEY hPubKey = NULL;
	if (!CryptImportPublicKeyInfo(hCryptProv, X509_ASN_ENCODING, &(pCert->pCertInfo->SubjectPublicKeyInfo), &hPubKey))
		return -1;
	//if (!CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, 0))
	//	return -1;

	LPCSTR pszData = "123";
	DWORD dwDataLen = strlen(pszData) + 1;
	BYTE* pbEncode = new BYTE[260];
	memcpy_s(pbEncode, 256, pszData, dwDataLen);
	if (!CryptEncrypt(hPubKey, NULL, TRUE, 0, pbEncode, &dwDataLen, 256))
		return -1;

	BYTE* pbDecoded = new BYTE[260];
	memcpy_s(pbDecoded, 256, pbEncode, dwDataLen);
	if (!CryptDecrypt(hPrvKey, NULL, TRUE, 0, pbDecoded, &dwDataLen))
		return -1;

	delete[] pbEncode;
	delete[] pbDecoded;
	CryptDestroyKey(hPubKey);
	CryptDestroyKey(hPrvKey);
	CryptReleaseContext(hCryptProv);
	CertFreeCertificateContext(pCert);
	CertCloseStore(hStore);
	return 0;
}

你可能感兴趣的:(加密,encoding,null,byte,include,delete)