繁体   English   中英

如何使用.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.

那么,如何使用私钥? 这是有关文件的要点

如何在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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM