Sample code for 30+ languages & platforms
Delphi DLL Requires Chilkat v11.6.0+

Azure Key Vault: Create and Export a CSR for an External CA

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 certificate_subject, such as CN=example.test. Creates a nonexportable RSA-2048 certificate key with 12-month validity and no key reuse. Requires certificates/create and certificates/get. HTTP 202 means accepted, not complete; polling is bounded to 30 requests and a 120-second checked deadline, with per-request timeouts. Issuer Unknown leaves issuance pending. Stops when a CSR is available, verifies its signature, and exports PEM to qa_output/request.csr. Submit it to your CA separately, then use the merge example. Never rerun create merely to resume polling.

Microsoft reference

Chilkat Delphi DLL Downloads

Delphi DLL
var
success: Boolean;
stringCompare: HCkStringBuilder;
config: HCkJsonObject;
stringMatch1: Boolean;
validate1: HCkStringBuilder;
alphabet1: HCkStringBuilder;
charIndex1: Integer;
vaultName: HCkStringBuilder;
letters: HCkStringBuilder;
origin: HCkStringBuilder;
http: HCkHttp;
request: HCkHttpRequest;
response: HCkHttpResponse;
result: HCkJsonObject;
token: HCkJsonObject;
stringMatch2: Boolean;
stringMatch3: Boolean;
expires: HCkDateTime;
now: HCkDateTime;
stringMatch4: Boolean;
validate42: HCkStringBuilder;
alphabet42: HCkStringBuilder;
charIndex42: Integer;
resourceBase: HCkStringBuilder;
stringMatch5: Boolean;
files: HCkFileAccess;
body: HCkJsonObject;
createUrl: HCkStringBuilder;
pendingUrl: HCkStringBuilder;
started: HCkDateTime;
pollNow: HCkDateTime;
ready: Boolean;
polls: Integer;
stringMatch6: Boolean;
stringMatch7: Boolean;
stringMatch8: Boolean;
stringMatch9: Boolean;
stringMatch10: Boolean;
csrDer: HCkBinData;
csrPem: HCkStringBuilder;
csr: HCkCsr;

begin
success := False;

stringCompare := CkStringBuilder_Create();
//  Assumes Chilkat is unlocked. See Global Unlock Sample.
//  Keep this configuration private, outside public web content and source control.
config := CkJsonObject_Create();
CkJsonObject_putStrict(config,True);
success := CkJsonObject_LoadFile(config,'qa_data/azure/keyvault.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not load private Key Vault configuration.');
    Exit;
  end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(config,'vault_name'));
stringMatch1 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(config,'vault_name') <> 1) or (stringMatch1 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid vault_name.');
    Exit;
  end;
validate1 := CkStringBuilder_Create();
alphabet1 := CkStringBuilder_Create();
success := CkStringBuilder_Append(validate1,CkJsonObject__stringOf(config,'vault_name'));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not validate vault_name.');
    Exit;
  end;
success := CkStringBuilder_Append(alphabet1,'abcdefghijklmnopqrstuvwxyz0123456789-');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not initialize validation.');
    Exit;
  end;
if ((CkStringBuilder_getLength(validate1) < 3) or (CkStringBuilder_getLength(validate1) > 24)) then
  begin
    Memo1.Lines.Add('Invalid vault_name length.');
    Exit;
  end;
charIndex1 := 0;
while (charIndex1 < CkStringBuilder_getLength(validate1)) do
  begin
    if (CkStringBuilder_Contains(alphabet1,CkStringBuilder__getRange(validate1,charIndex1,1,False),True) <> True) then
      begin
        Memo1.Lines.Add('Invalid character in vault_name.');
        Exit;
      end;
    charIndex1 := charIndex1 + 1;
  end;

vaultName := CkStringBuilder_Create();
CkStringBuilder_Append(vaultName,CkJsonObject__stringOf(config,'vault_name'));
letters := CkStringBuilder_Create();
CkStringBuilder_Append(letters,'abcdefghijklmnopqrstuvwxyz');
if ((CkStringBuilder_Contains(letters,CkStringBuilder__getRange(vaultName,0,1,False),True) <> True) or (CkStringBuilder_EndsWith(vaultName,'-',True) = True) or (CkStringBuilder_Contains(vaultName,'--',True) = True)) then
  begin
    Memo1.Lines.Add('Invalid vault_name.');
    Exit;
  end;
origin := CkStringBuilder_Create();
success := CkStringBuilder_Append(origin,'https://');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not construct URL or identifier.');
    Exit;
  end;
success := CkStringBuilder_Append(origin,CkJsonObject__stringOf(config,'vault_name'));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not construct URL or identifier.');
    Exit;
  end;
success := CkStringBuilder_Append(origin,'.vault.azure.net');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not construct URL or identifier.');
    Exit;
  end;
http := CkHttp_Create();
CkHttp_putRequireSslCertVerify(http,True);
CkHttp_putFollowRedirects(http,False);
CkHttp_putConnectTimeout(http,20);
CkHttp_putReadTimeout(http,60);
CkHttp_putVerboseLogging(http,False);
request := CkHttpRequest_Create();
CkHttpRequest_putHttpVerb(request,'GET');
response := CkHttpResponse_Create();
result := CkJsonObject_Create();
CkJsonObject_putStrict(result,True);
//  First run Get a Key Vault access token.
token := CkJsonObject_Create();
CkJsonObject_putStrict(token,True);
success := CkJsonObject_LoadFile(token,'qa_data/tokens/azureKeyVaultToken.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not read the private token file.');
    Exit;
  end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(token,'access_token'));
stringMatch2 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(token,'access_token') <> 1) or (stringMatch2 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid access_token.');
    Exit;
  end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(token,'expires_at'));
stringMatch3 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(token,'expires_at') <> 1) or (stringMatch3 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid expires_at.');
    Exit;
  end;
expires := CkDateTime_Create();
now := CkDateTime_Create();
success := CkDateTime_SetFromTimestamp(expires,CkJsonObject__stringOf(token,'expires_at'));
if (success <> True) then
  begin
    Memo1.Lines.Add('Invalid token expiration.');
    Exit;
  end;
CkHttp_putAuthToken(http,CkJsonObject__stringOf(token,'access_token'));
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(config,'cert_name'));
stringMatch4 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(config,'cert_name') <> 1) or (stringMatch4 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid cert_name.');
    Exit;
  end;
validate42 := CkStringBuilder_Create();
alphabet42 := CkStringBuilder_Create();
success := CkStringBuilder_Append(validate42,CkJsonObject__stringOf(config,'cert_name'));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not validate cert_name.');
    Exit;
  end;
success := CkStringBuilder_Append(alphabet42,'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not initialize validation.');
    Exit;
  end;
if ((CkStringBuilder_getLength(validate42) < 1) or (CkStringBuilder_getLength(validate42) > 127)) then
  begin
    Memo1.Lines.Add('Invalid cert_name length.');
    Exit;
  end;
charIndex42 := 0;
while (charIndex42 < CkStringBuilder_getLength(validate42)) do
  begin
    if (CkStringBuilder_Contains(alphabet42,CkStringBuilder__getRange(validate42,charIndex42,1,False),True) <> True) then
      begin
        Memo1.Lines.Add('Invalid character in cert_name.');
        Exit;
      end;
    charIndex42 := charIndex42 + 1;
  end;

resourceBase := CkStringBuilder_Create();
success := CkStringBuilder_Append(resourceBase,CkStringBuilder__getAsString(origin));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not construct URL or identifier.');
    Exit;
  end;
success := CkStringBuilder_Append(resourceBase,'/certificates/');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not construct URL or identifier.');
    Exit;
  end;
success := CkStringBuilder_Append(resourceBase,CkJsonObject__stringOf(config,'cert_name'));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not construct URL or identifier.');
    Exit;
  end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(config,'certificate_subject'));
stringMatch5 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(config,'certificate_subject') <> 1) or (stringMatch5 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid certificate_subject.');
    Exit;
  end;
files := CkFileAccess_Create();
if (CkFileAccess_FileExists(files,'qa_output/request.csr') = True) then
  begin
    Memo1.Lines.Add('Output exists; choose another private output path.');
    Exit;
  end;
body := CkJsonObject_Create();
success := CkJsonObject_UpdateString(body,'policy.key_props.kty','RSA');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set policy.key_props.kty.');
    Exit;
  end;
success := CkJsonObject_UpdateInt(body,'policy.key_props.key_size',2048);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set key size.');
    Exit;
  end;
success := CkJsonObject_UpdateBool(body,'policy.key_props.exportable',False);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set exportability.');
    Exit;
  end;
success := CkJsonObject_UpdateBool(body,'policy.key_props.reuse_key',False);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set reuse policy.');
    Exit;
  end;
success := CkJsonObject_UpdateString(body,'policy.secret_props.contentType','application/x-pkcs12');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set policy.secret_props.contentType.');
    Exit;
  end;
success := CkJsonObject_UpdateString(body,'policy.x509_props.subject',CkJsonObject__stringOf(config,'certificate_subject'));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set policy.x509_props.subject.');
    Exit;
  end;
success := CkJsonObject_UpdateInt(body,'policy.x509_props.validity_months',12);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set validity.');
    Exit;
  end;
success := CkJsonObject_UpdateString(body,'policy.issuer.name','Unknown');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set policy.issuer.name.');
    Exit;
  end;
createUrl := CkStringBuilder_Create();
success := CkStringBuilder_Append(createUrl,CkStringBuilder__getAsString(resourceBase));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not construct URL or identifier.');
    Exit;
  end;
success := CkStringBuilder_Append(createUrl,'/create?api-version=2026-04-01');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not construct URL or identifier.');
    Exit;
  end;
success := CkDateTime_SetFromCurrentSystemTime(now);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not read current time.');
    Exit;
  end;
if (CkDateTime_DiffSeconds(expires,now) <= 60) then
  begin
    Memo1.Lines.Add('Token is expired or near expiration. Obtain a new token before continuing.');
    Exit;
  end;
success := CkHttp_HttpJson(http,'POST',CkStringBuilder__getAsString(createUrl),body,'application/json',response);
if (success <> True) then
  begin
    Memo1.Lines.Add('Request failed; reconcile uncertain writes before retrying.');
    Exit;
  end;
if (CkHttpResponse_getStatusCode(response) <> 202) then
  begin
    Memo1.Lines.Add('Unexpected HTTP status; inspect request ID and diagnostics privately. Reconcile writes before retrying.');
    Exit;
  end;
success := CkJsonObject_Load(result,CkHttpResponse__bodyStr(response));
if (success <> True) then
  begin
    Memo1.Lines.Add('Invalid JSON response.');
    Exit;
  end;
pendingUrl := CkStringBuilder_Create();
success := CkStringBuilder_Append(pendingUrl,CkStringBuilder__getAsString(resourceBase));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not construct URL or identifier.');
    Exit;
  end;
success := CkStringBuilder_Append(pendingUrl,'/pending?api-version=2026-04-01');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not construct URL or identifier.');
    Exit;
  end;
started := CkDateTime_Create();
pollNow := CkDateTime_Create();
success := CkDateTime_SetFromCurrentSystemTime(started);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not start polling deadline.');
    Exit;
  end;
ready := False;
polls := 0;
while ((ready <> True) and (polls < 30)) do
  begin
    polls := polls + 1;
    success := CkDateTime_SetFromCurrentSystemTime(pollNow);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not read time.');
        Exit;
      end;
    if (CkDateTime_DiffSeconds(pollNow,started) >= 120) then
      begin
        Memo1.Lines.Add('Polling deadline reached; operation may still be pending. Resume GET polling, do not recreate.');
        Exit;
      end;
    success := CkDateTime_SetFromCurrentSystemTime(now);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not read current time.');
        Exit;
      end;
    if (CkDateTime_DiffSeconds(expires,now) <= 60) then
      begin
        Memo1.Lines.Add('Token is expired or near expiration. Obtain a new token before continuing.');
        Exit;
      end;
    CkHttpRequest_putHttpVerb(request,'GET');
    success := CkHttp_HttpReq(http,CkStringBuilder__getAsString(pendingUrl),request,response);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Request did not complete; inspect diagnostics privately.');
        Exit;
      end;
    if (CkHttpResponse_getStatusCode(response) <> 200) then
      begin
        Memo1.Lines.Add('Unexpected HTTP status; inspect request ID and diagnostics privately. Reconcile writes before retrying.');
        Exit;
      end;
    success := CkJsonObject_Load(result,CkHttpResponse__bodyStr(response));
    if (success <> True) then
      begin
        Memo1.Lines.Add('Invalid JSON response.');
        Exit;
      end;
    CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(result,'status'));
    stringMatch6 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
    if ((CkJsonObject_JsonTypeOf(result,'status') <> 1) or (stringMatch6 = True)) then
      begin
        Memo1.Lines.Add('Missing or invalid status.');
        Exit;
      end;
    CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(result,'status'));
    stringMatch7 := CkStringBuilder_ContentsEqual(stringCompare,'inProgress',True);
    CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(result,'status'));
    stringMatch8 := CkStringBuilder_ContentsEqual(stringCompare,'completed',True);
    if ((stringMatch7 <> True) and (stringMatch8 <> True)) then
      begin
        Memo1.Lines.Add('Certificate operation failed, was cancelled, or returned an unknown status.');
        Exit;
      end;
    if (CkJsonObject_JsonTypeOf(result,'csr') = 1) then
      begin
        CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(result,'csr'));
        stringMatch9 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
        if (stringMatch9 <> True) then
          begin
            ready := True;
          end;
      end;
    if (ready <> True) then
      begin
        CkHttp_SleepMs(http,2000);
      end;
  end;

if (ready <> True) then
  begin
    Memo1.Lines.Add('Poll limit reached; resume polling without repeating creation.');
    Exit;
  end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(result,'csr'));
stringMatch10 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(result,'csr') <> 1) or (stringMatch10 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid csr.');
    Exit;
  end;
csrDer := CkBinData_Create();
success := CkBinData_AppendEncoded(csrDer,CkJsonObject__stringOf(result,'csr'),'base64');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not decode CSR.');
    Exit;
  end;
csrPem := CkStringBuilder_Create();
success := CkStringBuilder_Append(csrPem,'-----BEGIN CERTIFICATE REQUEST-----' + #10);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not construct URL or identifier.');
    Exit;
  end;
success := CkStringBuilder_Append(csrPem,CkBinData__getEncoded(csrDer,'base64'));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not construct URL or identifier.');
    Exit;
  end;
success := CkStringBuilder_Append(csrPem,#10 + '-----END CERTIFICATE REQUEST-----' + #10);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not construct URL or identifier.');
    Exit;
  end;
csr := CkCsr_Create();
success := CkCsr_LoadCsrPem(csr,CkStringBuilder__getAsString(csrPem));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not parse CSR.');
    Exit;
  end;
success := CkCsr_VerifyCsr(csr);
if (success <> True) then
  begin
    Memo1.Lines.Add('CSR signature verification failed.');
    Exit;
  end;
success := CkStringBuilder_WriteFile(csrPem,'qa_output/request.csr','utf-8',False);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not save CSR.');
    Exit;
  end;
Memo1.Lines.Add('Example completed.');

CkStringBuilder_Dispose(stringCompare);
CkJsonObject_Dispose(config);
CkStringBuilder_Dispose(validate1);
CkStringBuilder_Dispose(alphabet1);
CkStringBuilder_Dispose(vaultName);
CkStringBuilder_Dispose(letters);
CkStringBuilder_Dispose(origin);
CkHttp_Dispose(http);
CkHttpRequest_Dispose(request);
CkHttpResponse_Dispose(response);
CkJsonObject_Dispose(result);
CkJsonObject_Dispose(token);
CkDateTime_Dispose(expires);
CkDateTime_Dispose(now);
CkStringBuilder_Dispose(validate42);
CkStringBuilder_Dispose(alphabet42);
CkStringBuilder_Dispose(resourceBase);
CkFileAccess_Dispose(files);
CkJsonObject_Dispose(body);
CkStringBuilder_Dispose(createUrl);
CkStringBuilder_Dispose(pendingUrl);
CkDateTime_Dispose(started);
CkDateTime_Dispose(pollNow);
CkBinData_Dispose(csrDer);
CkStringBuilder_Dispose(csrPem);
CkCsr_Dispose(csr);