Sample code for 30+ languages & platforms
Ruby 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 Ruby Downloads

Ruby
require 'chilkat'

success = false

stringCompare = Chilkat::CkStringBuilder.new()
#  Assumes Chilkat is unlocked. See Global Unlock Sample.
#  Keep this configuration private, outside public web content and source control.
config = Chilkat::CkJsonObject.new()
config.put_Strict(true)
success = config.LoadFile("qa_data/azure/keyvault.json")
if (success != true)
    print "Could not load private Key Vault configuration." + "\n";
    exit
end

stringCompare.SetString(config.stringOf("vault_name"))
stringMatch1 = stringCompare.ContentsEqual("",true)
if ((config.JsonTypeOf("vault_name") != 1) or (stringMatch1 == true))
    print "Missing or invalid vault_name." + "\n";
    exit
end

validate1 = Chilkat::CkStringBuilder.new()
alphabet1 = Chilkat::CkStringBuilder.new()
success = validate1.Append(config.stringOf("vault_name"))
if (success != true)
    print "Could not validate vault_name." + "\n";
    exit
end

success = alphabet1.Append("abcdefghijklmnopqrstuvwxyz0123456789-")
if (success != true)
    print "Could not initialize validation." + "\n";
    exit
end

if ((validate1.get_Length() < 3) or (validate1.get_Length() > 24))
    print "Invalid vault_name length." + "\n";
    exit
end

charIndex1 = 0
while (charIndex1 < validate1.get_Length())
    if (alphabet1.Contains(validate1.getRange(charIndex1,1,false),true) != true)
        print "Invalid character in vault_name." + "\n";
        exit
    end

    charIndex1 = charIndex1 + 1
end
vaultName = Chilkat::CkStringBuilder.new()
vaultName.Append(config.stringOf("vault_name"))
letters = Chilkat::CkStringBuilder.new()
letters.Append("abcdefghijklmnopqrstuvwxyz")
if ((letters.Contains(vaultName.getRange(0,1,false),true) != true) or (vaultName.EndsWith("-",true) == true) or (vaultName.Contains("--",true) == true))
    print "Invalid vault_name." + "\n";
    exit
end

origin = Chilkat::CkStringBuilder.new()
success = origin.Append("https://")
if (success != true)
    print "Could not construct URL or identifier." + "\n";
    exit
end

success = origin.Append(config.stringOf("vault_name"))
if (success != true)
    print "Could not construct URL or identifier." + "\n";
    exit
end

success = origin.Append(".vault.azure.net")
if (success != true)
    print "Could not construct URL or identifier." + "\n";
    exit
end

http = Chilkat::CkHttp.new()
http.put_RequireSslCertVerify(true)
http.put_FollowRedirects(false)
http.put_ConnectTimeout(20)
http.put_ReadTimeout(60)
http.put_VerboseLogging(false)
request = Chilkat::CkHttpRequest.new()
request.put_HttpVerb("GET")
response = Chilkat::CkHttpResponse.new()
result = Chilkat::CkJsonObject.new()
result.put_Strict(true)
#  First run Get a Key Vault access token.
token = Chilkat::CkJsonObject.new()
token.put_Strict(true)
success = token.LoadFile("qa_data/tokens/azureKeyVaultToken.json")
if (success != true)
    print "Could not read the private token file." + "\n";
    exit
end

stringCompare.SetString(token.stringOf("access_token"))
stringMatch2 = stringCompare.ContentsEqual("",true)
if ((token.JsonTypeOf("access_token") != 1) or (stringMatch2 == true))
    print "Missing or invalid access_token." + "\n";
    exit
end

stringCompare.SetString(token.stringOf("expires_at"))
stringMatch3 = stringCompare.ContentsEqual("",true)
if ((token.JsonTypeOf("expires_at") != 1) or (stringMatch3 == true))
    print "Missing or invalid expires_at." + "\n";
    exit
end

expires = Chilkat::CkDateTime.new()
now = Chilkat::CkDateTime.new()
success = expires.SetFromTimestamp(token.stringOf("expires_at"))
if (success != true)
    print "Invalid token expiration." + "\n";
    exit
end

http.put_AuthToken(token.stringOf("access_token"))
stringCompare.SetString(config.stringOf("cert_name"))
stringMatch4 = stringCompare.ContentsEqual("",true)
if ((config.JsonTypeOf("cert_name") != 1) or (stringMatch4 == true))
    print "Missing or invalid cert_name." + "\n";
    exit
end

validate2 = Chilkat::CkStringBuilder.new()
alphabet2 = Chilkat::CkStringBuilder.new()
success = validate2.Append(config.stringOf("cert_name"))
if (success != true)
    print "Could not validate cert_name." + "\n";
    exit
end

success = alphabet2.Append("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-")
if (success != true)
    print "Could not initialize validation." + "\n";
    exit
end

if ((validate2.get_Length() < 1) or (validate2.get_Length() > 127))
    print "Invalid cert_name length." + "\n";
    exit
end

charIndex2 = 0
while (charIndex2 < validate2.get_Length())
    if (alphabet2.Contains(validate2.getRange(charIndex2,1,false),true) != true)
        print "Invalid character in cert_name." + "\n";
        exit
    end

    charIndex2 = charIndex2 + 1
end
if (config.JsonTypeOf("pfx_password") != 1)
    print "Missing pfx_password string; empty is allowed for an unprotected PFX." + "\n";
    exit
end

cert = Chilkat::CkCert.new()
success = cert.LoadPfxFile("qa_data/pfx/myCertAndKey.pfx",config.stringOf("pfx_password"))
if (success != true)
    print "Could not load PFX; inspect diagnostics privately." + "\n";
    exit
end

privateKey = Chilkat::CkPrivateKey.new()
success = cert.GetPrivateKey(privateKey)
if (success != true)
    print "PFX must contain a usable private key." + "\n";
    exit
end

#  Inspect only the PUBLIC JWK. Never print or export a private JWK for key inspection.
publicKey = Chilkat::CkPublicKey.new()
success = privateKey.ToPublicKey(publicKey)
if (success != true)
    print "Could not get the public key." + "\n";
    exit
end

publicJwk = publicKey.getJwk()
if (publicKey.get_LastMethodSuccess() != true)
    print "Could not inspect the public key." + "\n";
    exit
end

keyInfo = Chilkat::CkJsonObject.new()
keyInfo.put_Strict(true)
success = keyInfo.Load(publicJwk)
if (success != true)
    print "Invalid public JWK." + "\n";
    exit
end

supported = false
stringCompare.SetString(keyInfo.stringOf("kty"))
stringMatch5 = stringCompare.ContentsEqual("RSA",true)
if (stringMatch5 == true)
    supported = (privateKey.get_BitLength() == 2048) or (privateKey.get_BitLength() == 3072) or (privateKey.get_BitLength() == 4096)
end

stringCompare.SetString(keyInfo.stringOf("kty"))
stringMatch6 = stringCompare.ContentsEqual("EC",true)
if (stringMatch6 == true)
    stringCompare.SetString(keyInfo.stringOf("crv"))
    stringMatch7 = stringCompare.ContentsEqual("P-256",true)
    stringCompare.SetString(keyInfo.stringOf("crv"))
    stringMatch8 = stringCompare.ContentsEqual("P-384",true)
    stringCompare.SetString(keyInfo.stringOf("crv"))
    stringMatch9 = stringCompare.ContentsEqual("P-521",true)
    if ((stringMatch7 == true) or (stringMatch8 == true) or (stringMatch9 == true))
        supported = true
    end

end

if (supported != true)
    print "This example supports RSA 2048/3072/4096 and NIST P-256/P-384/P-521." + "\n";
    exit
end

pfxBytes = Chilkat::CkBinData.new()
success = pfxBytes.LoadFile("qa_data/pfx/myCertAndKey.pfx")
if (success != true)
    print "Could not read the PFX." + "\n";
    exit
end

body = Chilkat::CkJsonObject.new()
success = body.UpdateString("value",pfxBytes.getEncoded("base64"))
if (success != true)
    print "Could not set value." + "\n";
    exit
end

success = body.UpdateString("pwd",config.stringOf("pfx_password"))
if (success != true)
    print "Could not set pwd." + "\n";
    exit
end

success = body.UpdateString("policy.key_props.kty",keyInfo.stringOf("kty"))
if (success != true)
    print "Could not set policy.key_props.kty." + "\n";
    exit
end

success = body.UpdateBool("policy.key_props.exportable",false)
if (success != true)
    print "Could not set nonexportable policy." + "\n";
    exit
end

success = body.UpdateBool("policy.key_props.reuse_key",false)
if (success != true)
    print "Could not set key reuse policy." + "\n";
    exit
end

success = body.UpdateString("policy.secret_props.contentType","application/x-pkcs12")
if (success != true)
    print "Could not set policy.secret_props.contentType." + "\n";
    exit
end

stringCompare.SetString(keyInfo.stringOf("kty"))
stringMatch10 = stringCompare.ContentsEqual("RSA",true)
if (stringMatch10 == true)
    success = body.UpdateInt("policy.key_props.key_size",privateKey.get_BitLength())
    if (success != true)
        print "Could not set RSA key size." + "\n";
        exit
    end

else
    success = body.UpdateString("policy.key_props.crv",keyInfo.stringOf("crv"))
    if (success != true)
        print "Could not set policy.key_props.crv." + "\n";
        exit
    end

end

importUrl = Chilkat::CkStringBuilder.new()
success = importUrl.Append(origin.getAsString())
if (success != true)
    print "Could not construct URL or identifier." + "\n";
    exit
end

success = importUrl.Append("/certificates/")
if (success != true)
    print "Could not construct URL or identifier." + "\n";
    exit
end

success = importUrl.Append(config.stringOf("cert_name"))
if (success != true)
    print "Could not construct URL or identifier." + "\n";
    exit
end

success = importUrl.Append("/import?api-version=2026-04-01")
if (success != true)
    print "Could not construct URL or identifier." + "\n";
    exit
end

success = now.SetFromCurrentSystemTime()
if (success != true)
    print "Could not read current time." + "\n";
    exit
end

if (expires.DiffSeconds(now) <= 60)
    print "Token is expired or near expiration. Obtain a new token before continuing." + "\n";
    exit
end

success = http.HttpJson("POST",importUrl.getAsString(),body,"application/json",response)
if (success != true)
    print "Request failed or its outcome is uncertain. Reconcile a write before retrying." + "\n";
    exit
end

if (response.get_StatusCode() != 200)
    print "HTTP status: " + response.get_StatusCode().to_s() + "\n";
    print "Request ID: " + response.getHeaderField("x-ms-request-id") + "\n";
    #  Do not print full response bodies, tokens, or diagnostic logs.
    print "Request failed. Inspect private diagnostics; reconcile writes before retrying." + "\n";
    exit
end

success = result.Load(response.bodyStr())
if (success != true)
    print "Expected a well-formed JSON response." + "\n";
    exit
end

certificateBase = Chilkat::CkStringBuilder.new()
success = certificateBase.Append(origin.getAsString())
if (success != true)
    print "Could not construct URL or identifier." + "\n";
    exit
end

success = certificateBase.Append("/certificates/")
if (success != true)
    print "Could not construct URL or identifier." + "\n";
    exit
end

success = certificateBase.Append(config.stringOf("cert_name"))
if (success != true)
    print "Could not construct URL or identifier." + "\n";
    exit
end

bundlePrefix = Chilkat::CkStringBuilder.new()
success = bundlePrefix.Append(certificateBase.getAsString())
if (success != true)
    print "Could not construct URL or identifier." + "\n";
    exit
end

success = bundlePrefix.Append("/")
if (success != true)
    print "Could not construct URL or identifier." + "\n";
    exit
end

stringCompare.SetString(result.stringOf("id"))
stringMatch11 = stringCompare.ContentsEqual("",true)
if ((result.JsonTypeOf("id") != 1) or (stringMatch11 == true))
    print "Missing or invalid id." + "\n";
    exit
end

stringCompare.SetString(result.stringOf("kid"))
stringMatch12 = stringCompare.ContentsEqual("",true)
if ((result.JsonTypeOf("kid") != 1) or (stringMatch12 == true))
    print "Missing or invalid kid." + "\n";
    exit
end

stringCompare.SetString(result.stringOf("cer"))
stringMatch13 = stringCompare.ContentsEqual("",true)
if ((result.JsonTypeOf("cer") != 1) or (stringMatch13 == true))
    print "Missing or invalid cer." + "\n";
    exit
end

certificateVersionId = Chilkat::CkStringBuilder.new()
success = certificateVersionId.Append(result.stringOf("id"))
if (success != true)
    print "Could not construct URL or identifier." + "\n";
    exit
end

if (certificateVersionId.StartsWith(bundlePrefix.getAsString(),true) != true)
    print "Returned identifier is outside the expected vault/resource." + "\n";
    exit
end

certificateVersion = certificateVersionId.getRange(bundlePrefix.get_Length(),certificateVersionId.get_Length() - bundlePrefix.get_Length(),false)
validate7 = Chilkat::CkStringBuilder.new()
alphabet7 = Chilkat::CkStringBuilder.new()
success = validate7.Append(certificateVersion)
if (success != true)
    print "Could not validate resource identifier." + "\n";
    exit
end

success = alphabet7.Append("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-")
if (success != true)
    print "Could not initialize validation." + "\n";
    exit
end

if ((validate7.get_Length() < 1) or (validate7.get_Length() > 127))
    print "Invalid resource identifier length." + "\n";
    exit
end

charIndex7 = 0
while (charIndex7 < validate7.get_Length())
    if (alphabet7.Contains(validate7.getRange(charIndex7,1,false),true) != true)
        print "Invalid character in resource identifier." + "\n";
        exit
    end

    charIndex7 = charIndex7 + 1
end
keyPrefix = Chilkat::CkStringBuilder.new()
success = keyPrefix.Append(origin.getAsString())
if (success != true)
    print "Could not construct URL or identifier." + "\n";
    exit
end

success = keyPrefix.Append("/keys/")
if (success != true)
    print "Could not construct URL or identifier." + "\n";
    exit
end

keyTailId = Chilkat::CkStringBuilder.new()
success = keyTailId.Append(result.stringOf("kid"))
if (success != true)
    print "Could not construct URL or identifier." + "\n";
    exit
end

if (keyTailId.StartsWith(keyPrefix.getAsString(),true) != true)
    print "Returned identifier is outside the expected vault/resource." + "\n";
    exit
end

keyTail = keyTailId.getRange(keyPrefix.get_Length(),keyTailId.get_Length() - keyPrefix.get_Length(),false)
keyTailParts = Chilkat::CkStringBuilder.new()
success = keyTailParts.Append(keyTail)
if (success != true)
    print "Could not construct URL or identifier." + "\n";
    exit
end

keyTailName = keyTailParts.getBefore("/",false)
keyTailVersion = keyTailParts.getAfterFinal("/",false)
validate8 = Chilkat::CkStringBuilder.new()
alphabet8 = Chilkat::CkStringBuilder.new()
success = validate8.Append(keyTailName)
if (success != true)
    print "Could not validate resource name." + "\n";
    exit
end

success = alphabet8.Append("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-")
if (success != true)
    print "Could not initialize validation." + "\n";
    exit
end

if ((validate8.get_Length() < 1) or (validate8.get_Length() > 127))
    print "Invalid resource name length." + "\n";
    exit
end

charIndex8 = 0
while (charIndex8 < validate8.get_Length())
    if (alphabet8.Contains(validate8.getRange(charIndex8,1,false),true) != true)
        print "Invalid character in resource name." + "\n";
        exit
    end

    charIndex8 = charIndex8 + 1
end
validate9 = Chilkat::CkStringBuilder.new()
alphabet9 = Chilkat::CkStringBuilder.new()
success = validate9.Append(keyTailVersion)
if (success != true)
    print "Could not validate resource version." + "\n";
    exit
end

success = alphabet9.Append("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-")
if (success != true)
    print "Could not initialize validation." + "\n";
    exit
end

if ((validate9.get_Length() < 1) or (validate9.get_Length() > 127))
    print "Invalid resource version length." + "\n";
    exit
end

charIndex9 = 0
while (charIndex9 < validate9.get_Length())
    if (alphabet9.Contains(validate9.getRange(charIndex9,1,false),true) != true)
        print "Invalid character in resource version." + "\n";
        exit
    end

    charIndex9 = charIndex9 + 1
end
keyTailCanonical = Chilkat::CkStringBuilder.new()
success = keyTailCanonical.Append(keyTailName)
if (success != true)
    print "Could not construct URL or identifier." + "\n";
    exit
end

success = keyTailCanonical.Append("/")
if (success != true)
    print "Could not construct URL or identifier." + "\n";
    exit
end

success = keyTailCanonical.Append(keyTailVersion)
if (success != true)
    print "Could not construct URL or identifier." + "\n";
    exit
end

stringCompare.SetString(keyTail)
stringMatch14 = stringCompare.ContentsEqual(keyTailCanonical.getAsString(),true)
if (stringMatch14 != true)
    print "Expected a versioned resource identifier." + "\n";
    exit
end

certificateId = result.stringOf("id")
keyId = result.stringOf("kid")
remoteCert = Chilkat::CkCert.new()
success = remoteCert.LoadFromBase64(result.stringOf("cer"))
if (success != true)
    print "Could not load the returned public certificate." + "\n";
    exit
end

sourceDer = cert.getEncoded()
if (cert.get_LastMethodSuccess() != true)
    print "Could not encode source certificate." + "\n";
    exit
end

importedDer = remoteCert.getEncoded()
if (remoteCert.get_LastMethodSuccess() != true)
    print "Could not encode imported certificate." + "\n";
    exit
end

stringCompare.SetString(sourceDer)
stringMatch15 = stringCompare.ContentsEqual(importedDer,true)
if (stringMatch15 != true)
    print "Imported certificate does not match the PFX leaf certificate." + "\n";
    exit
end

print "Imported certificate ID: " + certificateId + "\n";
print "Backing key ID: " + keyId + "\n";