Get a Certificate Including the Private Key

Azure Key Vault certificates are a great way to manage certificates. They allow you to set policies, automatically renew near-expiring certificates, and permit cryptographic operations with access to the private key. There are times, however, when you may want to download and use the entire certificate - including the private key - locally. You might have a legacy application, for example, that needs access to a key pair.

Caution

We recommend you keep cryptographic operations using the private key - including decryption, signing, and unwrapping - in Key Vault to minimize access to the private and mitigate possible breaches with a properly secured Key Vault.

Note

The functions CertificateClient.DownloadCertificate and CertificateClient.DownloadCertificateAsync were added in Azure.Security.KeyVault.Certificates 4.2.0. Those new functions effectively replace this sample, though we have retained this sample that shows some best practices and to notify any developers redirected here of these new functions.

Key Vault stores the public key as a managed key but the entire key pair including the private key - if created or imported as exportable - as a secret. This example shows you how download the key pair and uses it to encrypt and decrypt a plain text message.

Getting Started

This sample requires creating a certificate with an exportable private key. You'll also need to download and install the Azure CLI.

  1. Log into Azure using the CLI:

    az login
    
  2. Create a Key Vault if you haven't already:

    az keyvault create -n <KeyVaultName> -g <ResourceGroupName> -l <Location>
    
  3. Create a certificate policy. You can get the default policy for a self-signed certificate as shown below:

    Note

    Saving program output to a variable may vary depending on your shell.

    p=$(az keyvault certificate get-default-policy)
    echo $p
    
  4. Create a certificate using that policy:

    az keyvault certificate create --vault-name <KeyVaultName> -n <CertificateName> -p "$p"
    

Building the Sample

To build the sample:

  1. Install .NET Core 3.1 or newer.

  2. Run in the project directory:

    dotnet build
    

Running the Sample

You can either run the executable you just build, or build and run the project at the same time:

dotnet run -- --vault-name <KeyVaultName> -n <CertificateName> -m "Message you want to encrypt and decrypt"

The sample will get information about the specified certificate, download the key pair as a secret, then encrypt and decrypt your message as a test.