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
| Function | Library | Description |
|---|---|---|
BCryptGenerateSymmetricKey | Bcrypt.dll | Creates a symmetric key from a hash or raw key material. |
BCryptImportKeyPair | Bcrypt.dll | Imports an asymmetric key pair (RSA/ECC) from a BLOB. |
BCryptExportKey | Bcrypt.dll | Exports a key to a BLOB for storage or transfer. |
BCryptDestroyKey | Bcrypt.dll | Frees a key object and releases resources. |
CryptAcquireContext | Advapi32.dll | Obtains a handle to a CSP (Cryptographic Service Provider). |
CryptImportKey | Advapi32.dll | Imports a key into a CSP. |
CryptExportKey | Advapi32.dll | Exports a key from a CSP. |
CryptReleaseContext | Advapi32.dll | Releases 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).