Fetching a Private Key From An Azure Key Vault Certificate

If you create a private certificate in Azure Key Vault and use the fancy features like auto rotation, you might like to be able to fetch the private key from the vault and rehydrate it as a X509Certificate2 class in your C# code.

Here is how you do that:

KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetToken));
var certificateBundle = await keyVaultClient.GetCertificateAsync(certificateIdentifier);
var certficiateSecret = await keyVaultClient.GetSecretAsync(certificateBundle.SecretIdentifier.Identifier);
byte[] certificateDecoded = Convert.FromBase64String(certficiateSecret.Value);
var certificate = new X509Certificate2(certificateDecoded, password: "");

The Certificate Bundle passed back from the GetCertificateAsync call has a .Cer property, however that is just the bytes for the pubic key, if you do this:

var publicCertificate = new X509Certificate2(certificateBundle.Cer);

The X509Certificate2 instance will only contain the public key.  Instead you need to fetch the full secret and decode it to bytes, once you do that the only other thing you need to know is that Azure Key Vault stores the private certificate with a blank password.

GetToken is a method above, that the Key Vault Client uses to fetch the authication that will be used to access both the certificate and the secrets.  Notice the caller needs both secrets Get, and certificate Get access policy set in the portal for the Azure Key Vault.  

For More Information About How GetToken Works https://docs.microsoft.com/en-us/azure/key-vault/key-vault-developers-guide

{6230289B-5BEE-409e-932A-2F01FA407A92}


Comments

Popular posts from this blog

Yet once more into the breech (of altered programming logic)

Simple WP7 Mango App for Background Tasks, Toast, and Tiles: Code Explanation

How to convert SVG data to a Png Image file Using InkScape