Fetch certificates and private keys from Azure Keyvault via Azure CLI

Published: by

  • Categories:

It's that time of the year again when I got time to write a new post. Today, I was looking for a quick tutorial to fetch secrets from Azure CLI but didn't find any so I guess, there's an opportunity to write a post about it.

Considering we have the basic Azure keyvault setup and the secrets already exist in Keyvault, below are the steps on how to retrieve secrets from keyvault.

Not printings outputs to save the trouble of cleaning up the output.

List keyvaults

$ az keyvault list

Listing certs in a keyvault

$ az keyvault certificate list --vault-name {vault_name}

Download public key from a keyvault

The above command will give you id in return for all certificates that exist in that keyvault, we'll be reusing that in our next command.

$ az keyvault certificate download --id 'https://{vault_name}.vault.azure.net/certificates/test-www-foo-com' -f public.crt

The above command gives you the public key in the PEM format.

Download the private key in PEM format

Keyvault returns the certificate in base64 encoded pfx file.

# Download private key (Secret) in base64 encoded format
$ az keyvault secret show --vault-name {vault_name} --id 'https://{vault_name}.vault.azure.net/secrets/test-www-foo-com' | jq .value -r > encoded.data

# base64 decode the secret
$ cat encoded.data | base64 -D > secret.pfx

# Get the PEM formatted cert out
$ openssl pkcs12 -in secret.pfx -out pkey.key

Verify the public key and private key pair

Modulus for the private key and public key should be same.

# Modulus should be the same for below 2 commands.
$ openssl x509 -in pkey.key -noout -modulus
$ openssl x509 -in pkey.key -noout -modulus