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

Azure Key Vault: Merge an Issued Certificate Chain

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 to the name with a pending external-CA request. Load the previously exported CSR and private qa_data/azure/issued-chain.json containing only x5c: an array of standard-base64 DER certificates, leaf first. Validates the CSR signature and leaf public-key match before merging. Requires certificates/create; the service validates the pending request relationship. HTTP 201 returns the merged certificate. This does not establish CA trust or validate all chain constraints locally. Keep the original request available for recovery from uncertain outcomes.

Microsoft reference

Chilkat B4X Downloads

B4X
Dim success As Boolean = False

Dim stringCompare As ChilkatStringBuilder
stringCompare.Initialize
'  Assumes Chilkat is unlocked. See Global Unlock Sample.
'  Keep this configuration private, outside public web content and source control.
Dim config As ChilkatJsonObject
config.Initialize
config.Strict = True
success = config.LoadFile("qa_data/azure/keyvault.json")
If success <> True Then
    Log("Could not load private Key Vault configuration.")
    Return
End If

stringCompare.SetString(config.StringOf("vault_name"))
Dim stringMatch1 As Boolean = stringCompare.ContentsEqual("", True)
If (config.JsonTypeOf("vault_name") <> 1) Or (stringMatch1 = True) Then
    Log("Missing or invalid vault_name.")
    Return
End If

Dim validate1 As ChilkatStringBuilder
validate1.Initialize
Dim alphabet1 As ChilkatStringBuilder
alphabet1.Initialize
success = validate1.Append(config.StringOf("vault_name"))
If success <> True Then
    Log("Could not validate vault_name.")
    Return
End If

success = alphabet1.Append("abcdefghijklmnopqrstuvwxyz0123456789-")
If success <> True Then
    Log("Could not initialize validation.")
    Return
End If

If (validate1.Length < 3) Or (validate1.Length > 24) Then
    Log("Invalid vault_name length.")
    Return
End If

Dim charIndex1 As Int = 0
Do While (charIndex1 < validate1.Length)
    If alphabet1.Contains(validate1.GetRange(charIndex1, 1, False), True) <> True Then
        Log("Invalid character in vault_name.")
        Return
    End If

    charIndex1 = charIndex1 + 1
Loop
Dim vaultName As ChilkatStringBuilder
vaultName.Initialize
vaultName.Append(config.StringOf("vault_name"))
Dim letters As ChilkatStringBuilder
letters.Initialize
letters.Append("abcdefghijklmnopqrstuvwxyz")
If (letters.Contains(vaultName.GetRange(0, 1, False), True) <> True) Or (vaultName.EndsWith("-", True) = True) Or (vaultName.Contains("--", True) = True) Then
    Log("Invalid vault_name.")
    Return
End If

Dim origin As ChilkatStringBuilder
origin.Initialize
success = origin.Append("https://")
If success <> True Then
    Log("Could not construct URL or identifier.")
    Return
End If

success = origin.Append(config.StringOf("vault_name"))
If success <> True Then
    Log("Could not construct URL or identifier.")
    Return
End If

success = origin.Append(".vault.azure.net")
If success <> True Then
    Log("Could not construct URL or identifier.")
    Return
End If

Dim http As ChilkatHttp
http.Initialize("http")
http.RequireSslCertVerify = True
http.FollowRedirects = False
http.ConnectTimeout = 20
http.ReadTimeout = 60
http.VerboseLogging = False
Dim request As ChilkatHttpRequest
request.Initialize
request.HttpVerb = "GET"
Dim response As ChilkatHttpResponse
response.Initialize
Dim result As ChilkatJsonObject
result.Initialize
result.Strict = True
'  First run Get a Key Vault access token.
Dim token As ChilkatJsonObject
token.Initialize
token.Strict = True
success = token.LoadFile("qa_data/tokens/azureKeyVaultToken.json")
If success <> True Then
    Log("Could not read the private token file.")
    Return
End If

stringCompare.SetString(token.StringOf("access_token"))
Dim stringMatch2 As Boolean = stringCompare.ContentsEqual("", True)
If (token.JsonTypeOf("access_token") <> 1) Or (stringMatch2 = True) Then
    Log("Missing or invalid access_token.")
    Return
End If

stringCompare.SetString(token.StringOf("expires_at"))
Dim stringMatch3 As Boolean = stringCompare.ContentsEqual("", True)
If (token.JsonTypeOf("expires_at") <> 1) Or (stringMatch3 = True) Then
    Log("Missing or invalid expires_at.")
    Return
End If

Dim expires As ChilkatDateTime
expires.Initialize
Dim now As ChilkatDateTime
now.Initialize
success = expires.SetFromTimestamp(token.StringOf("expires_at"))
If success <> True Then
    Log("Invalid token expiration.")
    Return
End If

http.AuthToken = token.StringOf("access_token")
stringCompare.SetString(config.StringOf("cert_name"))
Dim stringMatch4 As Boolean = stringCompare.ContentsEqual("", True)
If (config.JsonTypeOf("cert_name") <> 1) Or (stringMatch4 = True) Then
    Log("Missing or invalid cert_name.")
    Return
End If

Dim validate43 As ChilkatStringBuilder
validate43.Initialize
Dim alphabet43 As ChilkatStringBuilder
alphabet43.Initialize
success = validate43.Append(config.StringOf("cert_name"))
If success <> True Then
    Log("Could not validate cert_name.")
    Return
End If

success = alphabet43.Append("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-")
If success <> True Then
    Log("Could not initialize validation.")
    Return
End If

If (validate43.Length < 1) Or (validate43.Length > 127) Then
    Log("Invalid cert_name length.")
    Return
End If

Dim charIndex43 As Int = 0
Do While (charIndex43 < validate43.Length)
    If alphabet43.Contains(validate43.GetRange(charIndex43, 1, False), True) <> True Then
        Log("Invalid character in cert_name.")
        Return
    End If

    charIndex43 = charIndex43 + 1
Loop
Dim resourceBase As ChilkatStringBuilder
resourceBase.Initialize
success = resourceBase.Append(origin.GetAsString)
If success <> True Then
    Log("Could not construct URL or identifier.")
    Return
End If

success = resourceBase.Append("/certificates/")
If success <> True Then
    Log("Could not construct URL or identifier.")
    Return
End If

success = resourceBase.Append(config.StringOf("cert_name"))
If success <> True Then
    Log("Could not construct URL or identifier.")
    Return
End If

Dim csrPem As ChilkatStringBuilder
csrPem.Initialize
success = csrPem.LoadFile("qa_output/request.csr", "utf-8")
If success <> True Then
    Log("Could not load the saved CSR.")
    Return
End If

Dim csr As ChilkatCsr
csr.Initialize
success = csr.LoadCsrPem(csrPem.GetAsString)
If success <> True Then
    Log("Invalid CSR.")
    Return
End If

success = csr.VerifyCsr
If success <> True Then
    Log("Invalid CSR signature.")
    Return
End If

Dim csrKey As ChilkatPublicKey
csrKey.Initialize
success = csr.GetPublicKey(csrKey)
If success <> True Then
    Log("Could not get CSR public key.")
    Return
End If

Dim expectedJwk As String = csrKey.GetJwk
If csrKey.LastMethodSuccess <> True Then
    Log("Could not encode CSR key.")
    Return
End If

Dim body As ChilkatJsonObject
body.Initialize
body.Strict = True
success = body.LoadFile("qa_data/azure/issued-chain.json")
If success <> True Then
    Log("Could not load issued chain.")
    Return
End If

If (body.JsonTypeOf("x5c") <> 4) Or (body.SizeOfArray("x5c") < 1) Then
    Log("Expected nonempty x5c array, leaf first.")
    Return
End If

Dim index As Int = 0
Dim issued As ChilkatCert
issued.Initialize("issued")
Do While (index < body.SizeOfArray("x5c"))
    body.I = index
    stringCompare.SetString(body.StringOf("x5c[i]"))
    Dim stringMatch5 As Boolean = stringCompare.ContentsEqual("", True)
    If (body.JsonTypeOf("x5c[i]") <> 1) Or (stringMatch5 = True) Then
        Log("Missing or invalid x5c[i].")
        Return
    End If

    success = issued.LoadFromBase64(body.StringOf("x5c[i]"))
    If success <> True Then
        Log("Invalid certificate in chain.")
        Return
    End If

    If index = 0 Then
        Dim leafKey As ChilkatPublicKey
        leafKey.Initialize
        success = issued.GetPublicKey(leafKey)
        If success <> True Then
            Log("Could not read leaf public key.")
            Return
        End If

        Dim actualJwk As String = leafKey.GetJwk
        If leafKey.LastMethodSuccess <> True Then
            Log("Could not encode leaf public key.")
            Return
        End If

        stringCompare.SetString(actualJwk)
        Dim stringMatch6 As Boolean = stringCompare.ContentsEqual(expectedJwk, True)
        If stringMatch6 <> True Then
            Log("Issued leaf certificate does not match the CSR.")
            Return
        End If

    End If

    index = index + 1
Loop
Dim mergeUrl As ChilkatStringBuilder
mergeUrl.Initialize
success = mergeUrl.Append(resourceBase.GetAsString)
If success <> True Then
    Log("Could not construct URL or identifier.")
    Return
End If

success = mergeUrl.Append("/pending/merge?api-version=2026-04-01")
If success <> True Then
    Log("Could not construct URL or identifier.")
    Return
End If

success = now.SetFromCurrentSystemTime
If success <> True Then
    Log("Could not read current time.")
    Return
End If

If expires.DiffSeconds(now) <= 60 Then
    Log("Token is expired or near expiration. Obtain a new token before continuing.")
    Return
End If

success = http.HttpJson("POST", mergeUrl.GetAsString, body, "application/json", response)
If success <> True Then
    Log("Request failed; reconcile uncertain writes before retrying.")
    Return
End If

If response.StatusCode <> 201 Then
    Log("Unexpected HTTP status; inspect request ID and diagnostics privately. Reconcile writes before retrying.")
    Return
End If

success = result.Load(response.BodyStr)
If success <> True Then
    Log("Invalid JSON response.")
    Return
End If

stringCompare.SetString(result.StringOf("id"))
Dim stringMatch7 As Boolean = stringCompare.ContentsEqual("", True)
If (result.JsonTypeOf("id") <> 1) Or (stringMatch7 = True) Then
    Log("Missing or invalid id.")
    Return
End If

Dim returnedVersion44Prefix As ChilkatStringBuilder
returnedVersion44Prefix.Initialize
success = returnedVersion44Prefix.Append(resourceBase.GetAsString)
If success <> True Then
    Log("Could not construct URL or identifier.")
    Return
End If

success = returnedVersion44Prefix.Append("/")
If success <> True Then
    Log("Could not construct URL or identifier.")
    Return
End If

Dim returnedVersion44Id As ChilkatStringBuilder
returnedVersion44Id.Initialize
success = returnedVersion44Id.Append(result.StringOf("id"))
If success <> True Then
    Log("Could not construct URL or identifier.")
    Return
End If

If returnedVersion44Id.StartsWith(returnedVersion44Prefix.GetAsString, True) <> True Then
    Log("Returned identifier is outside the expected vault/resource.")
    Return
End If

Dim returnedVersion44 As String = returnedVersion44Id.GetRange(returnedVersion44Prefix.Length, returnedVersion44Id.Length - returnedVersion44Prefix.Length, False)
Dim validate45 As ChilkatStringBuilder
validate45.Initialize
Dim alphabet45 As ChilkatStringBuilder
alphabet45.Initialize
success = validate45.Append(returnedVersion44)
If success <> True Then
    Log("Could not validate resource identifier.")
    Return
End If

success = alphabet45.Append("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-")
If success <> True Then
    Log("Could not initialize validation.")
    Return
End If

If (validate45.Length < 1) Or (validate45.Length > 127) Then
    Log("Invalid resource identifier length.")
    Return
End If

Dim charIndex45 As Int = 0
Do While (charIndex45 < validate45.Length)
    If alphabet45.Contains(validate45.GetRange(charIndex45, 1, False), True) <> True Then
        Log("Invalid character in resource identifier.")
        Return
    End If

    charIndex45 = charIndex45 + 1
Loop
stringCompare.SetString(result.StringOf("cer"))
Dim stringMatch8 As Boolean = stringCompare.ContentsEqual("", True)
If (result.JsonTypeOf("cer") <> 1) Or (stringMatch8 = True) Then
    Log("Missing or invalid cer.")
    Return
End If

success = issued.LoadFromBase64(result.StringOf("cer"))
If success <> True Then
    Log("Invalid merged certificate.")
    Return
End If

Dim mergedDer As String = issued.GetEncoded
If issued.LastMethodSuccess <> True Then
    Log("Could not encode merged certificate.")
    Return
End If

success = issued.LoadFromBase64(body.StringOf("x5c[0]"))
If success <> True Then
    Log("Invalid original leaf certificate.")
    Return
End If

Dim issuedDer As String = issued.GetEncoded
If issued.LastMethodSuccess <> True Then
    Log("Could not encode original leaf certificate.")
    Return
End If

stringCompare.SetString(mergedDer)
Dim stringMatch9 As Boolean = stringCompare.ContentsEqual(issuedDer, True)
If stringMatch9 <> True Then
    Log("Merged certificate does not match the issued leaf.")
    Return
End If

Log("Example completed.")