Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8627453
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T08:17:04+00:00 2026-06-12T08:17:04+00:00

How do i encrypt data using a certificate in the Microsoft Crypto API? i

  • 0

How do i encrypt data using a “certificate” in the Microsoft Crypto API?


i know how to encrypt data with the Microsoft Crypto API using AES encryption:

keyBlob.hdr.bType := PLAINTEXTKEYBLOB;
keyBlob.hdr.bVersion := CUR_BLOB_VERSION;
keyBlob.hdr.reserved := 0;
keyBlob.hdr.aiKeyAlg := CALG_AES_128;
keyBlob.cbKeySize := 16;
Move(data[0], keyBlob.key[0], 16);


/*
   Set ProviderName to either
   providerName = "Microsoft Enhanced RSA and AES Cryptographic Provider"
   providerName = "Microsoft Enhanced RSA and AES Cryptographic Provider (Prototype)"  //Windows XP and earlier
*/
MS_ENH_RSA_AES_PROV_W: WideString = 'Microsoft Enhanced RSA and AES Cryptographic Provider';
providerName := MS_ENH_RSA_AES_PROV_W;

CryptAcquireContextW(provider, nil, PWideChar(providerName), PROV_RSA_AES, CRYPT_VERIFYCONTEXT);
CryptImportKey(provider, PByte(@keyBlob), sizeof(keyBlob), 0, 0, importedKey);

mode := CRYPT_MODE_CBC;
CryptSetKeyParam(importedKey, KP_MODE, @mode, 0);

//CryptEncrypt encrypts in-place. Copy stuff to be encrypted into new byte buffer
utf8PlainText := TCrypt.WideStringToUTF8(szPlainText);
dataLen := Length(utf8PlainText);
bufferLen := dataLen+16; //allocate a buffer larger than we need to hold the data we want to encrypt
SetLength(data, bufferLen);
Move(utf8PlainText[1], data[0], dataLen);

if not CryptEncrypt(importedKey, 0, True, 0, @data[0], {var}dataLen, bufferLen) then
begin
   le := GetLastError;
   if le = ERROR_MORE_DATA  then
   begin
      /*
         If the buffer allocated for pbData is not large enough to hold the encrypted data,
         GetLastError returns ERROR_MORE_DATA and stores the required buffer size,
         in bytes, in the DWORD value pointed to by pdwDataLen.
      */
      bufferLen := dataLen;
      SetLength(data, bufferLen);
      CryptEncrypt(importedKey, 0, True, 0, @data[0], {var}dataLen, bufferLen);
   end;
   CryptDestroyKey(importedKey);
   CryptReleaseContext(provider, 0);
end;

Now i need to do the same thing, except rather than symmetric encryption i need to use a public-key to encrypt, and a private key to decrypt.


Note: It took 3 days to come up with those 15 lines of code for symmetric encryption. i’m hoping someone can same me from a week of banging my head against a wall, and i end up going down the wrong path thinking that i have to install OpenSSL. Even worse, if i try to call COM Objects from native code

Note: i only included the code example as a way to fill-up the question with irrelavent junk. Some people vote to close a question if it only contains one line.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T08:17:05+00:00Added an answer on June 12, 2026 at 8:17 am

    Microsoft Crypto API contain high-level functions for asymmetric encryption and decryption with certificates. Look at CryptEncryptessage and CryptDecryptMessage.

    In decryption case your CERT_CONTEXT must have a CERT_KEY_PROV_INFO_PROP_ID property.

    I can give you an examples of usage:

    const wchar_t message[] = L"This is a simple test message.";
    PCCERT_CONTEXT hCert = NULL;
    HCERTSTORE hStore = NULL;
    
    static bool openCertStoreMY(CDialog *parent)
    {
        if(!hStore)
        {
            hStore = CertOpenSystemStore(NULL, L"MY");
    
            if(!hStore)
            {
                parent->MessageBox(L"Cannot open \"MY\"", L"Error", MB_ICONERROR);
                return false;
            }
        }
    
        return true;
    }
    
    void CTestDlg::OnEncryptClicked()
    {
        if(!hCert)
        {
            if(!openCertStoreMY(this))
                return;
    
            hCert = CryptUIDlgSelectCertificateFromStore(hStore, GetSafeHwnd(), NULL, NULL, 0, 0, 0);
    
            if(!hCert)
                return;
        }
    
        CRYPT_ENCRYPT_MESSAGE_PARA params;
        memset(&params, 0, sizeof(CRYPT_ENCRYPT_MESSAGE_PARA));
        params.cbSize = sizeof(CRYPT_ENCRYPT_MESSAGE_PARA);
        params.dwMsgEncodingType = X509_ASN_ENCODING | PKCS_7_ASN_ENCODING;
        params.ContentEncryptionAlgorithm.pszObjId = "2.16.840.1.101.3.4.1.2"; //AES128
    
        DWORD msz;
        DWORD cbMsg = sizeof(message);
        const BYTE *pbMsg = (PBYTE)message;
        if(!CryptEncryptMessage(&params, 1, &hCert, pbMsg, cbMsg, NULL, &msz))
            return;
    
        PBYTE outBuf = new BYTE[msz];
        if(CryptEncryptMessage(&params, 1, &hCert, pbMsg, cbMsg, outBuf, &msz))
        {
            FILE *fil = _wfopen(filename, L"wb");
            if(fil)
            {
                fwrite(outBuf, 1, msz, fil);
                fclose(fil);
                MessageBox(L"Complete");
            }
            else
                MessageBox(L"Cannot open file", L"Error", MB_ICONERROR);
        }
    
        delete [] outBuf;
    }
    
    void CTestDlg::OnDecryptClicked()
    {
        if(!openCertStoreMY(this))
            return;
    
        CRYPT_DECRYPT_MESSAGE_PARA params;
        params.cbSize = sizeof(CRYPT_DECRYPT_MESSAGE_PARA);
        params.dwMsgAndCertEncodingType = X509_ASN_ENCODING | PKCS_7_ASN_ENCODING;
        params.cCertStore = 1;
        params.rghCertStore = &hStore;
        params.dwFlags = 0;
    
        DWORD cbMsg;
        PBYTE pbMsg;
    
        FILE *fil = _wfopen(filename, L"rb");
        if(fil)
        {
            fseek(fil, 0 ,2);
            cbMsg = ftell(fil);
            fseek(fil, 0, 0);
            pbMsg = new BYTE[cbMsg];
    
            fread(pbMsg, 1, cbMsg, fil);
            fclose(fil);
        } else {
            MessageBox(L"Cannot open file", L"Error", MB_ICONERROR);
            return;
        }
    
        DWORD msz;
        if(!CryptDecryptMessage(&params, pbMsg, cbMsg, NULL, &msz, NULL))
        {
            delete [] pbMsg;
            return;
        }
    
        PBYTE outBuf = new BYTE[msz];
        if(CryptDecryptMessage(&params, pbMsg, cbMsg, outBuf, &msz, NULL))
            MessageBox((LPCWSTR)outBuf);
    
        delete [] pbMsg;
        delete [] outBuf;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

The following code is a try to encrypt data using AES with asymmetric key:
Talking about javax.crypto.Cipher I was trying to encrypt data using Cipher.getInstance(RSA/None/NoPadding, BC) but I
I am trying to read from a file and encrypt the data using AES
i m writing one application which encrypt and decrypt data using AES (ECB) mode.
I'm using RSA private-public key encryption to encrypt data coming from server. The main
I need encrypt data using exactly the PKCS#1 V2.0 encryption method (defined in item
I'm currently using AES (256) with CBC mode to encrypt data. I store the
I am trying to encrypt data using AES (ECB) .How can i do it
I'm looking to encrypt some data using multiple ciphers (ie, AES, Serpent, Twofish...), and
I have the following python script to encrypt/decrypt data using AES 256, could you

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.