DEV Community

Antidisestablishmentarianism
Antidisestablishmentarianism

Posted on

1

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

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs