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

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

这是我用来检索秘密的function,它正在工作。

public static async Task 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连接到网站时,我收到以下exception: System.NotSupportedException: The server mode SSL must use a certificate with the associated private key.

那么,我该如何使用私钥? 这是有问题的文件的要点 。

我已经获得了如何在Azure Key Vault中序列化和反序列化PFX证书的帮助? 但在遵循它之后,我达到了这个状态。

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

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

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

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

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