DPAPI 输出缓冲区内存管理

DPAPI output buffer memory management

我在我的应用程序中使用 CryptProtectData()CryptUnprotectData() API 进行数据加密和解密。

阅读 API documentation,不清楚为什么 LocalFree() 需要在使用后针对输出缓冲区调用。该页面上的示例代码未调用 LocalFree(),是否未命中?

文档中还缺少什么(这个问题的主要原因)是,DPAPI 管理的输出如何 DATA_BLOB::pbData?我可以自己管理输出缓冲区的内存吗?如果可以,如何提前知道加密数据的输出缓冲区大小,以便分配足够大的缓冲区供CryptProtectData()CryptUnprotectData()使用?

这是我如何使用 CryptProtectData():

的代码片段
DATA_BLOB dataIn;
DATA_BLOB dataOut;
dataIn.pbData = (BYTE *)"Hello world";
dataIn.cbData = (DWORD)strlen((char*)pbDataInput);

if(CryptProtectData(&dataIn, NULL, NULL, NULL, NULL, 0, &dataOut))
{
    printf("Encrypted data size: %d", dataOut.cbData);
    // LocalFree(dataOut.pbData); // Is this needed? Why? How do I manage dataOut.pbData by myself?
}

Reading the API documentation, it's not clear why LocalFree() needs to be called against the output buffer after usage.

因为CryptProtectData()动态分配一个输出缓冲区给你,所以你用完后需要释放它。

The example code on that page does not invoke LocalFree(), is that a miss?

是的。

how is DATA_BLOB::pbData for the output managed by DPAPI? Can I manage the memory for the output buffer myself?

没有 CryptProtectData(),没有。您必须使用它为您提供的缓冲区。

如果您想使用自己的缓冲区,请改用 CryptProtectMemory()

If I can, how do I know the output buffer size of the encrypted data in advance so that I can allocate a large enough buffer for CryptProtectData() or CryptUnprotectData() to use?

CryptProtectData() 在分配动态输出缓冲区时为您处理。

CryptProtectMemory() 内联加密,对输入和输出使用相同的缓冲区。因此,您有责任确保缓冲区足够大以容纳输出。它的文档说:

[in] cbDataIn

Number of bytes of memory pointed to by the pData parameter to encrypt. The number of bytes must be a multiple of the CRYPTPROTECTMEMORY_BLOCK_SIZE constant defined in Wincrypt.h.

因此,您只需获取输入数据的大小并将其四舍五入为块大小的下一个倍数。