1
我如何使用Microsoft Crypto API中的「證書」加密數據?如何使用證書加密數據?
我知道如何使用AES加密與微軟的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;
現在我需要做同樣的事情,除了而非對稱加密,我需要使用一個公共 - 加密密鑰和私鑰解密。
注意:花了3天時間拿出這15行代碼的對稱加密。我希望有人可以同我從敲我的頭靠在牆上,一個星期,我最終會走上錯誤的道路想,我必須安裝OpenSSL的。更糟的是,如果我嘗試調用COM Objectsfrom native code
注意:我只包括了代碼示例,以此來填充了irrelavent垃圾的問題。如果只包含一行,某些人會投票結束一個問題。