【问题标题】:How to fetch certificate from keyvault?如何从密钥库中获取证书?
【发布时间】:2020-11-17 01:06:04
【问题描述】:

如果pfx 文件存储在文件共享中,这很容易:

new X509Certificate2(certificateFilePath, certificatePassword);

但是如何为存储在 Azure Keyvault 中的证书构造 X509Certificate2 对象?我找不到任何样品。我有用于密钥库的 ClientIdClientSecret

【问题讨论】:

    标签: asp.net-core certificate azure-keyvault


    【解决方案1】:

    我创建了这个 AzureKeyvaultHelper 类(我仍在使用 .NET 4.8 - 但我相信这也应该适用于 .NET Core):

    using System;
    using System.Security.Cryptography.X509Certificates;
    using Azure.Identity;
    using Azure.Security.KeyVault.Secrets;
    
    namespace AzureUtils
    {
        public class AzureKeyvaultHelper
        {
            private readonly string _tenantId;
            private readonly string _clientId;
            private readonly string _clientSecret;
    
            public AzureKeyvaultHelper(string tenantId, string clientId, string clientSecret)
            {
                _clientId = clientId;
                _clientSecret = clientSecret;
                _tenantId = tenantId;
            }
    
            public X509Certificate2 GetCertificate(string vaultName, string certName)
            {
                ClientSecretCredential credentials = new ClientSecretCredential(_tenantId, _clientId, _clientSecret);
                var client = new SecretClient(new Uri(vaultName), credentials);
    
                KeyVaultSecret secret = client.GetSecret(certName);
                byte[] certificate = Convert.FromBase64String(secret.Value);
    
                X509Certificate2 x509 = new X509Certificate2(certificate);
    
                return x509;
            }
        }
    }
    

    基本上,你需要

    • 包括Azure.IdentityAzure.Security.KeyVault.Secrets nuget 包
    • 向构造函数提供租户 ID、客户端 ID 和客户端密码,以启动并运行 SecretClient(在 Azure.Security.KeyVault.Secrets 中定义 - 用于 keyvault)

    完整获取证书的技巧(包括*.pfx 文件中的私有部分)是使用client.GetCertificate 调用,而是使用client.GetSecret 调用。 GetCertificate 调用将只返回证书的公共部分并删除任何私有组件。

    要传入的 vaultName 类似于 https://yourcustomname.vault.azure.netcertName 必须与您在 Azure Keyvault 中提供的证书名称相匹配。

    【讨论】:

    • 我很好奇,所以不能以同样的方式调用秘密和证书?
    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 2020-06-28
    • 1970-01-01
    • 1970-01-01
    • 2011-04-30
    • 2013-07-07
    • 2013-01-16
    • 1970-01-01
    相关资源
    最近更新 更多