#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; }