Search code examples
c++cryptoapi

Exemple using BCryptDeriveKeyPBKDF2 from MSDN


I don't find some simple exemple using BCryptDeriveKeyPBKDF2 function. I need to get key with PBKDF2 algorithm. I think it is symple action but i find very diffucult ways. I using CryptoApi Windows and i need get key.

Show me please how can i use this function to get key BCryptDeriveKeyPBKDF2 ?

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


Solution

  • I also had a hard time finding a simple example. I was finally able to create this:

    #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:;
    
    }