Use CryptoAPI for PKCS #1 format Encryption

Source: Internet
Author: User
#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;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.