Microsoft Docs - Windows Crypto API

Cryptography – Key Management

This documentation covers the Windows Key Management APIs available in the Crypt32.dll, Bcrypt.dll and Advapi32.dll libraries. Use these functions to create, import, export, and destroy cryptographic keys securely.

Namespaces

  • BCrypt – CNG (Cryptography Next Generation) primitives.
  • CryptoAPI – Legacy CryptoAPI functions.
  • CertificateStore – Certificate storage management.

Core Functions

FunctionLibraryDescription
BCryptGenerateSymmetricKeyBcrypt.dllCreates a symmetric key from a hash or raw key material.
BCryptImportKeyPairBcrypt.dllImports an asymmetric key pair (RSA/ECC) from a BLOB.
BCryptExportKeyBcrypt.dllExports a key to a BLOB for storage or transfer.
BCryptDestroyKeyBcrypt.dllFrees a key object and releases resources.
CryptAcquireContextAdvapi32.dllObtains a handle to a CSP (Cryptographic Service Provider).
CryptImportKeyAdvapi32.dllImports a key into a CSP.
CryptExportKeyAdvapi32.dllExports a key from a CSP.
CryptReleaseContextAdvapi32.dllReleases the CSP handle.

Using CNG to Generate an AES‑256 Key (JavaScript Example)

const { execSync } = require('child_process');

// Generate a random 256‑bit key using PowerShell (CNG)
const keyHex = execSync('powershell -Command "(New-Object byte[] 32 | ForEach-Object {Get-Random -Maximum 256}) -join \\" \\" "')
  .toString().trim()
  .split(' ')
  .map(b => parseInt(b,10).toString(16).padStart(2,'0'))
  .join('');

// Display the key
console.log("AES‑256 Key (hex):", keyHex);

This script demonstrates how to rely on the OS‑provided RNG (CNG) for key material. For production, use the native BCryptGenRandom API via a compiled addon.

Best Practices

  • Never store keys in plain text. Use DPAPI or Windows Credential Guard.
  • Prefer CNG over CryptoAPI for new development.
  • Zero‑out memory buffers after use with SecureZeroMemory.
  • Leverage hardware‑backed keys when available (TPM, HSM).