如何在 .NET Core 2 中使用存储在 Azure Key Vault 中的 PFX 证书中的私钥?

How do I use the private key from a PFX certificate stored in Azure Key Vault in .NET Core 2?

我用 C# 编写了一个 ASP.NET Core 2.0 网站并启用了 Facebook 身份验证,因此它需要 HTTPS。我正在使用本机 Kestrel Web 服务器来托管该站点,并设置了一个侦听器以根据 MS 的文档获取 PFX 证书。从 Key Vault 召回后,我似乎找不到让 Kestrel 识别私钥的方法。我知道它存在,因为我写了两个调试语句来表明它实际上存在。

这是我用来检索机密的函数,它正在运行。

        public static async Task<X509Certificate2> GetKeyVaultCert()
    {
        X509Certificate2 pfx;

        try
        {
            var kvClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetToken));
            var secret = await kvClient
                .GetSecretAsync("https://macscampvault.vault.azure.net/secrets/letsencrypt").ConfigureAwait(false);

            byte[] bytes;
            if(secret.ContentType == "application/x-pkcs12")
                bytes = Convert.FromBase64String(secret.Value);
            else
            {
                bytes = new byte[0];
                Console.WriteLine("secret is not PFX!!");
                throw new ArgumentException("This is not a PFX string!!");
            }
            var password = new SecureString();

            var coll = new X509Certificate2Collection();
            coll.Import(bytes, null, X509KeyStorageFlags.Exportable);
            pfx = coll[0];
// File output added in case I end up needing to write cert to container
//          File.WriteAllBytes(Directory.GetCurrentDirectory().ToString() + "/Macs.pfx", bytes);
            Console.WriteLine(pfx.HasPrivateKey);
            Console.WriteLine(pfx.GetRSAPrivateKey());

        }
        catch (Exception ex)
        {
            Console.WriteLine($"There was a problem during the key vault operation\n{ex.Message}");
            throw;
        }

        return pfx;
    }

赋值调用 pfx = coll[0]; 后的调试语句告诉我这个私钥存在,但是当我尝试使用 lynx https://localhost 连接到网站时,我收到以下异常: System.NotSupportedException: The server mode SSL must use a certificate with the associated private key.

那么,我该如何使用私钥呢?这是相关文件的 gist

我已经得到了的帮助,但是在跟随它之后,我到了这个状态。

在你的要点中,你有以下代码:

var keyVaultCert = GetKeyVaultCert().Result ??
    throw new ArgumentNullException("GetKeyVaultCert().Result");
pfx = new X509Certificate2(keyVaultCert.RawData);

那里的第二行删除了私钥,因为 RawData 属性 只是 returns DER 编码的 X.509 对象。

keyVaultCert 已经是带有私钥的 X509Certificate2,您可能只想使用它。

pfx = GetKeyVaultCert().Result ?? throw etc;