Are you frequently handling SSL/TLS certificates and struggling with multiple formats for different purposes? Managing certificates can be cumbersome, but Azure App Service Certificates streamline this process by automating various tasks involved in certificate management.
For individuals dealing with certificates regularly, understanding their crucial role in securing web applications is imperative. However, the intricacies of certificate management, from retrieval from Azure Key Vault to conversion for diverse uses, can be time-consuming and prone to errors. In this article, I’ll share code snippets that I commonly use to download certificates from Azure Key Vault and convert them into various formats.
Downloading a Certificate as a PFX from Azure Key Vault
1
2
3
4
5
6
7
8
9
10
11
| $kvname = 'your-key-vault-name'
$certname = 'your-cert-name'
$pfxpassword = -join ((65..90) + (97..122) + (48..57) | Get-Random -Count 50 | % {[char]$_})
$secret = (az keyvault secret show --name $certname --vault-name $kvname --query value -o tsv)
$bytes = [Convert]::FromBase64String($secret)
$pfx = New-Object Security.Cryptography.X509Certificates.X509Certificate2
$pfx.Import($bytes, $null, [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
$pfxProtectedBytes = $pfx.Export([Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12, $pfxpassword)
$pfxPath = [Environment]::GetFolderPath("Desktop") + "\your-cert-name.pfx"
[IO.File]::WriteAllBytes($pfxPath, $pfxProtectedBytes)
Write-Host "PFX Password: $pfxpassword"
|
1
| openssl pkcs12 -in your-cert-name.pfx -nocerts -out encrypted-key.pem
|
1
| openssl rsa -in encrypted-key.pem -out decrypted-key.key
|
1
| openssl pkcs12 -in your-cert-name.pfx -clcerts -nokeys -out certificate-name.crt
|
1
| openssl pkcs12 -in your-cert-name.pfx -cacerts -nokeys -chain -out ca-chain.pem
|
To exclude headers from the resulting PEM file, use the command: sed -ne ‘/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p’ before saving.
Combine the CA certificate and client certificate using: cat ca-chain.pem certificate-name.crt > certbundle.pem
1
| openssl pkcs12 -in your-cert-name.pfx -out your-cert-name.pem -nodes
|
Uploading to Azure Key Vault from Files
1
2
| az keyvault secret set --vault-name your-key-vault-name --name decrypted-key --file decrypted-key.key
az keyvault secret set --vault-name your-key-vault-name --name certificate-name --file certificate-name.crt
|