DEV Community

Antidisestablishmentarianism
Antidisestablishmentarianism

Posted on

A BCryptDeriveKeyPBKDF2 example in C++.

I had a heck of a time finding a simple example of this function. I eventually made my own...

#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:;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)