Sample code for 30+ languages & platforms
Unicode C++ Requires Chilkat v11.6.0+

Azure Key Vault: Import a PFX Certificate with the REST API

See more Azure Key Vault Examples

Requires Chilkat 11.6.0 or later. Keep qa_data/azure/keyvault.json and token/PFX files private, outside web content and source control, with access restricted to the application identity. Use placeholders replaced by your configuration, never commit credentials. Create output directories before running file-writing examples. These examples target Azure public-cloud vaults, not Managed HSM or sovereign-cloud endpoints.

Uses HTTPS and Key Vault data-plane API 2026-04-01. Configure vault_name and first run the client-credentials token example. It writes access_token and an expires_at UTC timestamp to qa_data/tokens/azureKeyVaultToken.json. Each request checks expiration; refresh is explicit. The sample stops on errors and does not retry. Production callers should handle 429/Retry-After and transient failures with bounded backoff, and reconcile uncertain writes. Redirects are disabled.

Set cert_name and string pfx_password; load a PFX containing the leaf certificate and its private key from qa_data/pfx/myCertAndKey.pfx. The sample accepts RSA 2048/3072/4096 and NIST EC P-256/P-384/P-521. Import creates a new version if the name already exists. Keep a protected backup and reconcile uncertain failures before retrying. Requires certificates/import. Keep PFX material, request bodies, and diagnostics private; only resource identifiers are printed. The returned leaf certificate is checked against the source.

Explicitly selects a nonexportable private-key policy and disables key reuse. Existing certificate policy constraints can reject incompatible imports; choose a new name or deliberately reconcile policy. This does not delete the original local PFX. The standard base64 request contains the entire PFX, protected in transit by verified TLS; the PFX password comes from private configuration.

Microsoft reference

Chilkat Unicode C++ Downloads

Unicode C++
#include <CkStringBuilderW.h>
#include <CkJsonObjectW.h>
#include <CkHttpW.h>
#include <CkHttpRequestW.h>
#include <CkHttpResponseW.h>
#include <CkDateTimeW.h>
#include <CkCertW.h>
#include <CkPrivateKeyW.h>
#include <CkPublicKeyW.h>
#include <CkBinDataW.h>

void ChilkatSample(void)
    {
    bool success = false;

    CkStringBuilderW stringCompare;
    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    //  Keep this configuration private, outside public web content and source control.
    CkJsonObjectW config;
    config.put_Strict(true);
    success = config.LoadFile(L"qa_data/azure/keyvault.json");
    if (success != true) {
        wprintf(L"Could not load private Key Vault configuration.\n");
        return;
    }

    stringCompare.SetString(config.stringOf(L"vault_name"));
    bool stringMatch1 = stringCompare.ContentsEqual(L"",true);
    if ((config.JsonTypeOf(L"vault_name") != 1) || (stringMatch1 == true)) {
        wprintf(L"Missing or invalid vault_name.\n");
        return;
    }

    CkStringBuilderW validate1;
    CkStringBuilderW alphabet1;
    success = validate1.Append(config.stringOf(L"vault_name"));
    if (success != true) {
        wprintf(L"Could not validate vault_name.\n");
        return;
    }

    success = alphabet1.Append(L"abcdefghijklmnopqrstuvwxyz0123456789-");
    if (success != true) {
        wprintf(L"Could not initialize validation.\n");
        return;
    }

    if ((validate1.get_Length() < 3) || (validate1.get_Length() > 24)) {
        wprintf(L"Invalid vault_name length.\n");
        return;
    }

    int charIndex1 = 0;
    while ((charIndex1 < validate1.get_Length())) {
        if (alphabet1.Contains(validate1.getRange(charIndex1,1,false),true) != true) {
            wprintf(L"Invalid character in vault_name.\n");
            return;
        }

        charIndex1 = charIndex1 + 1;
    }

    CkStringBuilderW vaultName;
    vaultName.Append(config.stringOf(L"vault_name"));
    CkStringBuilderW letters;
    letters.Append(L"abcdefghijklmnopqrstuvwxyz");
    if ((letters.Contains(vaultName.getRange(0,1,false),true) != true) || (vaultName.EndsWith(L"-",true) == true) || (vaultName.Contains(L"--",true) == true)) {
        wprintf(L"Invalid vault_name.\n");
        return;
    }

    CkStringBuilderW origin;
    success = origin.Append(L"https://");
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    success = origin.Append(config.stringOf(L"vault_name"));
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    success = origin.Append(L".vault.azure.net");
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    CkHttpW http;
    http.put_RequireSslCertVerify(true);
    http.put_FollowRedirects(false);
    http.put_ConnectTimeout(20);
    http.put_ReadTimeout(60);
    http.put_VerboseLogging(false);
    CkHttpRequestW request;
    request.put_HttpVerb(L"GET");
    CkHttpResponseW response;
    CkJsonObjectW result;
    result.put_Strict(true);
    //  First run Get a Key Vault access token.
    CkJsonObjectW token;
    token.put_Strict(true);
    success = token.LoadFile(L"qa_data/tokens/azureKeyVaultToken.json");
    if (success != true) {
        wprintf(L"Could not read the private token file.\n");
        return;
    }

    stringCompare.SetString(token.stringOf(L"access_token"));
    bool stringMatch2 = stringCompare.ContentsEqual(L"",true);
    if ((token.JsonTypeOf(L"access_token") != 1) || (stringMatch2 == true)) {
        wprintf(L"Missing or invalid access_token.\n");
        return;
    }

    stringCompare.SetString(token.stringOf(L"expires_at"));
    bool stringMatch3 = stringCompare.ContentsEqual(L"",true);
    if ((token.JsonTypeOf(L"expires_at") != 1) || (stringMatch3 == true)) {
        wprintf(L"Missing or invalid expires_at.\n");
        return;
    }

    CkDateTimeW expires;
    CkDateTimeW now;
    success = expires.SetFromTimestamp(token.stringOf(L"expires_at"));
    if (success != true) {
        wprintf(L"Invalid token expiration.\n");
        return;
    }

    http.put_AuthToken(token.stringOf(L"access_token"));
    stringCompare.SetString(config.stringOf(L"cert_name"));
    bool stringMatch4 = stringCompare.ContentsEqual(L"",true);
    if ((config.JsonTypeOf(L"cert_name") != 1) || (stringMatch4 == true)) {
        wprintf(L"Missing or invalid cert_name.\n");
        return;
    }

    CkStringBuilderW validate2;
    CkStringBuilderW alphabet2;
    success = validate2.Append(config.stringOf(L"cert_name"));
    if (success != true) {
        wprintf(L"Could not validate cert_name.\n");
        return;
    }

    success = alphabet2.Append(L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-");
    if (success != true) {
        wprintf(L"Could not initialize validation.\n");
        return;
    }

    if ((validate2.get_Length() < 1) || (validate2.get_Length() > 127)) {
        wprintf(L"Invalid cert_name length.\n");
        return;
    }

    int charIndex2 = 0;
    while ((charIndex2 < validate2.get_Length())) {
        if (alphabet2.Contains(validate2.getRange(charIndex2,1,false),true) != true) {
            wprintf(L"Invalid character in cert_name.\n");
            return;
        }

        charIndex2 = charIndex2 + 1;
    }

    if (config.JsonTypeOf(L"pfx_password") != 1) {
        wprintf(L"Missing pfx_password string; empty is allowed for an unprotected PFX.\n");
        return;
    }

    CkCertW cert;
    success = cert.LoadPfxFile(L"qa_data/pfx/myCertAndKey.pfx",config.stringOf(L"pfx_password"));
    if (success != true) {
        wprintf(L"Could not load PFX; inspect diagnostics privately.\n");
        return;
    }

    CkPrivateKeyW privateKey;
    success = cert.GetPrivateKey(privateKey);
    if (success != true) {
        wprintf(L"PFX must contain a usable private key.\n");
        return;
    }

    //  Inspect only the PUBLIC JWK. Never print or export a private JWK for key inspection.
    CkPublicKeyW publicKey;
    success = privateKey.ToPublicKey(publicKey);
    if (success != true) {
        wprintf(L"Could not get the public key.\n");
        return;
    }

    const wchar_t *publicJwk = publicKey.getJwk();
    if (publicKey.get_LastMethodSuccess() != true) {
        wprintf(L"Could not inspect the public key.\n");
        return;
    }

    CkJsonObjectW keyInfo;
    keyInfo.put_Strict(true);
    success = keyInfo.Load(publicJwk);
    if (success != true) {
        wprintf(L"Invalid public JWK.\n");
        return;
    }

    bool supported = false;
    stringCompare.SetString(keyInfo.stringOf(L"kty"));
    bool stringMatch5 = stringCompare.ContentsEqual(L"RSA",true);
    if (stringMatch5 == true) {
        supported = (privateKey.get_BitLength() == 2048) || (privateKey.get_BitLength() == 3072) || (privateKey.get_BitLength() == 4096);
    }

    stringCompare.SetString(keyInfo.stringOf(L"kty"));
    bool stringMatch6 = stringCompare.ContentsEqual(L"EC",true);
    if (stringMatch6 == true) {
        stringCompare.SetString(keyInfo.stringOf(L"crv"));
        bool stringMatch7 = stringCompare.ContentsEqual(L"P-256",true);
        stringCompare.SetString(keyInfo.stringOf(L"crv"));
        bool stringMatch8 = stringCompare.ContentsEqual(L"P-384",true);
        stringCompare.SetString(keyInfo.stringOf(L"crv"));
        bool stringMatch9 = stringCompare.ContentsEqual(L"P-521",true);
        if ((stringMatch7 == true) || (stringMatch8 == true) || (stringMatch9 == true)) {
            supported = true;
        }

    }

    if (supported != true) {
        wprintf(L"This example supports RSA 2048/3072/4096 and NIST P-256/P-384/P-521.\n");
        return;
    }

    CkBinDataW pfxBytes;
    success = pfxBytes.LoadFile(L"qa_data/pfx/myCertAndKey.pfx");
    if (success != true) {
        wprintf(L"Could not read the PFX.\n");
        return;
    }

    CkJsonObjectW body;
    success = body.UpdateString(L"value",pfxBytes.getEncoded(L"base64"));
    if (success != true) {
        wprintf(L"Could not set value.\n");
        return;
    }

    success = body.UpdateString(L"pwd",config.stringOf(L"pfx_password"));
    if (success != true) {
        wprintf(L"Could not set pwd.\n");
        return;
    }

    success = body.UpdateString(L"policy.key_props.kty",keyInfo.stringOf(L"kty"));
    if (success != true) {
        wprintf(L"Could not set policy.key_props.kty.\n");
        return;
    }

    success = body.UpdateBool(L"policy.key_props.exportable",false);
    if (success != true) {
        wprintf(L"Could not set nonexportable policy.\n");
        return;
    }

    success = body.UpdateBool(L"policy.key_props.reuse_key",false);
    if (success != true) {
        wprintf(L"Could not set key reuse policy.\n");
        return;
    }

    success = body.UpdateString(L"policy.secret_props.contentType",L"application/x-pkcs12");
    if (success != true) {
        wprintf(L"Could not set policy.secret_props.contentType.\n");
        return;
    }

    stringCompare.SetString(keyInfo.stringOf(L"kty"));
    bool stringMatch10 = stringCompare.ContentsEqual(L"RSA",true);
    if (stringMatch10 == true) {
        success = body.UpdateInt(L"policy.key_props.key_size",privateKey.get_BitLength());
        if (success != true) {
            wprintf(L"Could not set RSA key size.\n");
            return;
        }

    }
    else {
        success = body.UpdateString(L"policy.key_props.crv",keyInfo.stringOf(L"crv"));
        if (success != true) {
            wprintf(L"Could not set policy.key_props.crv.\n");
            return;
        }

    }

    CkStringBuilderW importUrl;
    success = importUrl.Append(origin.getAsString());
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    success = importUrl.Append(L"/certificates/");
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    success = importUrl.Append(config.stringOf(L"cert_name"));
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    success = importUrl.Append(L"/import?api-version=2026-04-01");
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    success = now.SetFromCurrentSystemTime();
    if (success != true) {
        wprintf(L"Could not read current time.\n");
        return;
    }

    if (expires.DiffSeconds(now) <= 60) {
        wprintf(L"Token is expired or near expiration. Obtain a new token before continuing.\n");
        return;
    }

    success = http.HttpJson(L"POST",importUrl.getAsString(),body,L"application/json",response);
    if (success != true) {
        wprintf(L"Request failed or its outcome is uncertain. Reconcile a write before retrying.\n");
        return;
    }

    if (response.get_StatusCode() != 200) {
        wprintf(L"HTTP status: %d\n",response.get_StatusCode());
        wprintf(L"Request ID: %s\n",response.getHeaderField(L"x-ms-request-id"));
        //  Do not print full response bodies, tokens, or diagnostic logs.
        wprintf(L"Request failed. Inspect private diagnostics; reconcile writes before retrying.\n");
        return;
    }

    success = result.Load(response.bodyStr());
    if (success != true) {
        wprintf(L"Expected a well-formed JSON response.\n");
        return;
    }

    CkStringBuilderW certificateBase;
    success = certificateBase.Append(origin.getAsString());
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    success = certificateBase.Append(L"/certificates/");
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    success = certificateBase.Append(config.stringOf(L"cert_name"));
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    CkStringBuilderW bundlePrefix;
    success = bundlePrefix.Append(certificateBase.getAsString());
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    success = bundlePrefix.Append(L"/");
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    stringCompare.SetString(result.stringOf(L"id"));
    bool stringMatch11 = stringCompare.ContentsEqual(L"",true);
    if ((result.JsonTypeOf(L"id") != 1) || (stringMatch11 == true)) {
        wprintf(L"Missing or invalid id.\n");
        return;
    }

    stringCompare.SetString(result.stringOf(L"kid"));
    bool stringMatch12 = stringCompare.ContentsEqual(L"",true);
    if ((result.JsonTypeOf(L"kid") != 1) || (stringMatch12 == true)) {
        wprintf(L"Missing or invalid kid.\n");
        return;
    }

    stringCompare.SetString(result.stringOf(L"cer"));
    bool stringMatch13 = stringCompare.ContentsEqual(L"",true);
    if ((result.JsonTypeOf(L"cer") != 1) || (stringMatch13 == true)) {
        wprintf(L"Missing or invalid cer.\n");
        return;
    }

    CkStringBuilderW certificateVersionId;
    success = certificateVersionId.Append(result.stringOf(L"id"));
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    if (certificateVersionId.StartsWith(bundlePrefix.getAsString(),true) != true) {
        wprintf(L"Returned identifier is outside the expected vault/resource.\n");
        return;
    }

    const wchar_t *certificateVersion = certificateVersionId.getRange(bundlePrefix.get_Length(),certificateVersionId.get_Length() - bundlePrefix.get_Length(),false);
    CkStringBuilderW validate7;
    CkStringBuilderW alphabet7;
    success = validate7.Append(certificateVersion);
    if (success != true) {
        wprintf(L"Could not validate resource identifier.\n");
        return;
    }

    success = alphabet7.Append(L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-");
    if (success != true) {
        wprintf(L"Could not initialize validation.\n");
        return;
    }

    if ((validate7.get_Length() < 1) || (validate7.get_Length() > 127)) {
        wprintf(L"Invalid resource identifier length.\n");
        return;
    }

    int charIndex7 = 0;
    while ((charIndex7 < validate7.get_Length())) {
        if (alphabet7.Contains(validate7.getRange(charIndex7,1,false),true) != true) {
            wprintf(L"Invalid character in resource identifier.\n");
            return;
        }

        charIndex7 = charIndex7 + 1;
    }

    CkStringBuilderW keyPrefix;
    success = keyPrefix.Append(origin.getAsString());
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    success = keyPrefix.Append(L"/keys/");
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    CkStringBuilderW keyTailId;
    success = keyTailId.Append(result.stringOf(L"kid"));
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    if (keyTailId.StartsWith(keyPrefix.getAsString(),true) != true) {
        wprintf(L"Returned identifier is outside the expected vault/resource.\n");
        return;
    }

    const wchar_t *keyTail = keyTailId.getRange(keyPrefix.get_Length(),keyTailId.get_Length() - keyPrefix.get_Length(),false);
    CkStringBuilderW keyTailParts;
    success = keyTailParts.Append(keyTail);
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    const wchar_t *keyTailName = keyTailParts.getBefore(L"/",false);
    const wchar_t *keyTailVersion = keyTailParts.getAfterFinal(L"/",false);
    CkStringBuilderW validate8;
    CkStringBuilderW alphabet8;
    success = validate8.Append(keyTailName);
    if (success != true) {
        wprintf(L"Could not validate resource name.\n");
        return;
    }

    success = alphabet8.Append(L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-");
    if (success != true) {
        wprintf(L"Could not initialize validation.\n");
        return;
    }

    if ((validate8.get_Length() < 1) || (validate8.get_Length() > 127)) {
        wprintf(L"Invalid resource name length.\n");
        return;
    }

    int charIndex8 = 0;
    while ((charIndex8 < validate8.get_Length())) {
        if (alphabet8.Contains(validate8.getRange(charIndex8,1,false),true) != true) {
            wprintf(L"Invalid character in resource name.\n");
            return;
        }

        charIndex8 = charIndex8 + 1;
    }

    CkStringBuilderW validate9;
    CkStringBuilderW alphabet9;
    success = validate9.Append(keyTailVersion);
    if (success != true) {
        wprintf(L"Could not validate resource version.\n");
        return;
    }

    success = alphabet9.Append(L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-");
    if (success != true) {
        wprintf(L"Could not initialize validation.\n");
        return;
    }

    if ((validate9.get_Length() < 1) || (validate9.get_Length() > 127)) {
        wprintf(L"Invalid resource version length.\n");
        return;
    }

    int charIndex9 = 0;
    while ((charIndex9 < validate9.get_Length())) {
        if (alphabet9.Contains(validate9.getRange(charIndex9,1,false),true) != true) {
            wprintf(L"Invalid character in resource version.\n");
            return;
        }

        charIndex9 = charIndex9 + 1;
    }

    CkStringBuilderW keyTailCanonical;
    success = keyTailCanonical.Append(keyTailName);
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    success = keyTailCanonical.Append(L"/");
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    success = keyTailCanonical.Append(keyTailVersion);
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    stringCompare.SetString(keyTail);
    bool stringMatch14 = stringCompare.ContentsEqual(keyTailCanonical.getAsString(),true);
    if (stringMatch14 != true) {
        wprintf(L"Expected a versioned resource identifier.\n");
        return;
    }

    const wchar_t *certificateId = result.stringOf(L"id");
    const wchar_t *keyId = result.stringOf(L"kid");
    CkCertW remoteCert;
    success = remoteCert.LoadFromBase64(result.stringOf(L"cer"));
    if (success != true) {
        wprintf(L"Could not load the returned public certificate.\n");
        return;
    }

    const wchar_t *sourceDer = cert.getEncoded();
    if (cert.get_LastMethodSuccess() != true) {
        wprintf(L"Could not encode source certificate.\n");
        return;
    }

    const wchar_t *importedDer = remoteCert.getEncoded();
    if (remoteCert.get_LastMethodSuccess() != true) {
        wprintf(L"Could not encode imported certificate.\n");
        return;
    }

    stringCompare.SetString(sourceDer);
    bool stringMatch15 = stringCompare.ContentsEqual(importedDer,true);
    if (stringMatch15 != true) {
        wprintf(L"Imported certificate does not match the PFX leaf certificate.\n");
        return;
    }

    wprintf(L"Imported certificate ID: %s\n",certificateId);
    wprintf(L"Backing key ID: %s\n",keyId);
    }