1

This is a keyvault related question. I stored a pfx cert (with private key) in keyvault. From my service principal I am trying to access the keyvault to get the cert. I am writing the following code to retrieve the pfx cert. But the cert file does not have private key ☹ I can’t get the private key file that I put in with all the authentications working:

        var keyVaultService = new KeyVaultService(keyVaultSettings);
        var pfx = await keyVaultService.GetKeyVaultSecretValue("test-cert");

        Assert.IsTrue(!string.IsNullOrEmpty(pfx));

        var bytes = Convert.FromBase64String(pfx);
        var coll = new X509Certificate2Collection();
        coll.Import(bytes, null, X509KeyStorageFlags.Exportable);
        var cert = coll[0];
        Assert.IsTrue(cert.HasPrivateKey); // Assert FAILS!!!
        var key = cert.PrivateKey.ToString();
        Console.WriteLine("private key: " + key);
  • I have had troubles like this myself, I won't post as an answer as I was using powershell but it might be related: https://stackoverflow.com/questions/43837362/keyvault-generated-certificate-with-exportable-private-key – Alex KeySmith Jul 27 '18 at 22:53

1 Answers1

0

Your code looks fine. There isn't much to it, but I tried it out quickly as well in a console app and it returned cert.HasPrivateKey as true.

I'm assuming you're specifying the right keyvaultsettings, and secret name will be exactly your certificate name.

I see 2 possible reasons:

  1. You're getting the right response from KeyVault, but losing it while converting to bytes. Example - look at this similar question - How do I use the private key from a PFX certificate stored in Azure Key Vault in .NET Core 2?

  2. You may want to check if you uploaded the certificate to KeyVault correctly. Is it possible that you didn't add the certificate to vault correctly? or added only the public cert portion of the pfx.

If either doesn't make sense, please share more detailed code or gist and it will be easier to tell.

Rohit Saigal
  • 9,317
  • 2
  • 20
  • 32
  • Here's an example of the secret url: "https://yourvaultname.vault.azure.net/secrets/certname/" – Rohit Saigal Jul 28 '18 at 02:48
  • Thanks for the answer. the wrong I did was I gave the secret name as the name of the certificate instead of the full secret identifier URL. I did this which was wrong: var secret = await keyVaultClient.GetSecretAsync("test-cert"); Instead when I did this, things started working: var secret = await keyVaultClient.GetSecretAsync("https://tycoonkeyvault.vault.azure.net/secrets/test-cert"); – Sairam Subramanian Gopal Jul 29 '18 at 05:58