使用 MSDN 中的 BCryptDeriveKeyPBKDF2 的示例

Exemple using BCryptDeriveKeyPBKDF2 from MSDN

我没有找到一些使用 BCryptDeriveKeyPBKDF2 函数的简单示例。 我需要使用 PBKDF2 算法获取密钥。我认为这是简单的动作,但我发现非常困难的方法。我使用 CryptoApi Windows 并且我需要获取密钥。

请告诉我如何使用此函数获取密钥 BCryptDeriveKeyPBKDF2?

https://docs.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptderivekeypbkdf2

我也很难找到一个简单的例子。我终于能够创建这个:

#pragma comment(lib, "bcrypt.lib")
#include <Windows.h>
#include <string>
#include <iostream>

int main()
{

    std::string password = "This is the password that will be encrypted";
    std::string salt = "EncryptionSalt";
    NTSTATUS Status;
    BYTE DerivedKey[64];

    BCRYPT_ALG_HANDLE handle;
    Status = BCryptOpenAlgorithmProvider(&handle, BCRYPT_SHA512_ALGORITHM, NULL, BCRYPT_ALG_HANDLE_HMAC_FLAG);

    if (Status != 0)
    {
        std::cout << "BCryptOpenAlgorithmProvider exited with error message " << Status;
        goto END;
    }

    Status = BCryptDeriveKeyPBKDF2(handle, (BYTE*)password.data(), password.length(), (BYTE*)salt.data(), 8, 2048, DerivedKey, 64, 0);

    if (Status != 0)
    {
        std::cout << "BCryptDeriveKeyPBKDF2 exited with error message " << Status;
        goto END;
    }

    else
        std::cout << "Operation completed successfully. Your encrypted key is in variable DerivedKey.";

    BCryptCloseAlgorithmProvider(handle, 0);

END:;

}