Windows Cryptography API Discussion

Alice Johnson
Sep 14, 2025 09:12 AM

I'm trying to use the CNG (Cryptography Next Generation) API to generate an RSA key pair. Below is a snippet that works on Windows 10 but throws an error on Windows Server 2012. Any ideas?

#include <windows.h>
#include <bcrypt.h>
#pragma comment(lib, "bcrypt.lib")

BCRYPT_ALG_HANDLE hAlg = NULL;
BCRYPT_KEY_HANDLE hKey = NULL;

NTSTATUS status = BCryptOpenAlgorithmProvider(&hAlg, BCRYPT_RSA_ALGORITHM, NULL, 0);
if (!BCRYPT_SUCCESS(status)) {
    wprintf(L"OpenAlgorithmProvider failed: 0x%08x\n", status);
    return 1;
}
status = BCryptGenerateKeyPair(hAlg, &hKey, 2048, 0);
if (!BCRYPT_SUCCESS(status)) {
    wprintf(L"GenerateKeyPair failed: 0x%08x\n", status);
    BCryptCloseAlgorithmProvider(hAlg,0);
    return 1;
}
BCryptFinalizeKeyPair(hKey,0);
wprintf(L"Key generated successfully.\n");
BCryptDestroyKey(hKey);
BCryptCloseAlgorithmProvider(hAlg,0);
return 0;
Michael Lee
Sep 14, 2025 10:45 AM

On Server 2012 you need to explicitly load the bcryptprimitives.dll library before opening the algorithm. Also make sure your project targets the correct SDK version.

HMODULE hMod = LoadLibraryW(L"bcryptprimitives.dll");
if (!hMod) {
    wprintf(L"Failed to load bcryptprimitives.dll\n");
    return 1;
}
... // rest of your code
Sara Patel
Sep 14, 2025 12:03 PM

If you're targeting .NET, the RSACng class simplifies this a lot. Example:

using System.Security.Cryptography;

using (var rsa = new RSACng(2048))
{
    byte[] publicKey = rsa.ExportSubjectPublicKeyInfo();
    Console.WriteLine(Convert.ToBase64String(publicKey));
}

Post a reply