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.