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;