使用CryptoApi做PKCS#1格式加密

#include "stdafx.h"
#include <windows.h>
#include <Wincrypt.h>

#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 = "<a><b>123</b></a>";
	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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值