如何使用Microsoft Crypto API 中的“证书”加密数据?
我知道如何使用 AES 加密使用 Microsoft Crypto API 加密数据:
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;
现在我需要做同样的事情,除了对称加密之外,我需要使用公钥进行加密,使用私钥进行解密。
注意:这 15 行对称加密代码花了 3 天时间。我希望有人能从我的头撞到墙上一周后和我一样,我最终走错了路,以为我必须安装OpenSSL。更糟糕的是,如果我尝试从本机代码调用COM 对象
注意:我只包含代码示例作为用无关垃圾填充问题的一种方式。如果某个问题仅包含一行,则有些人会投票结束该问题。