如何从keyvault获取证书?

问题描述 投票:0回答:2

如果

pfx
文件存储在文件共享中,则很简单:

new X509Certificate2(certificateFilePath, certificatePassword);

但是如何为存储在 Azure Keyvault 中的证书构建

X509Certificate2
对象?我找不到任何样本。我有钥匙库的
ClientId
ClientSecret

asp.net-core certificate azure-keyvault
2个回答
2
投票

我创建了这个

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.Identity
    Azure.Security.KeyVault.Secrets
    nuget 包
  • 向构造函数提供租户 ID、客户端 ID 和客户端密钥,以启动并运行
    SecretClient
    (在
    Azure.Security.KeyVault.Secrets
    - 用于 keyvault 中定义)

完全获取证书(包括

*.pfx
文件中的私有部分)的技巧是 not 使用
client.GetCertificate
调用 - 而是使用
client.GetSecret
调用。
GetCertificate
调用将仅返回证书的公共部分并删除任何私有部分。

要传入的

vaultName
类似于
https://yourcustomname.vault.azure.net
,并且
certName
必须与您在 Azure Keyvault 中为证书提供的名称相匹配。


0
投票

于 2021 年 6 月 16 日在 v4.2.0 中添加了对

Azure.Security.KeyVault.Certificates
的支持:

Azure.Security.KeyVault.Certificates 4.2.0 中添加了函数CertificateClient.DownloadCertificate 和CertificateClient.DownloadCertificateAsync。

https://learn.microsoft.com/en-us/samples/azure/azure-sdk-for-net/get-certificate-private-key/

https://learn.microsoft.com/en-us/dotnet/api/azure.security.keyvault.certificates.certificateclient.downloadcertificateasync?view=azure-dotnet

© www.soinside.com 2019 - 2024. All rights reserved.