如果
pfx
文件存储在文件共享中,则很简单:
new X509Certificate2(certificateFilePath, certificatePassword);
但是如何为存储在 Azure Keyvault 中的证书构建
X509Certificate2
对象?我找不到任何样本。我有钥匙库的 ClientId
和 ClientSecret
。
我创建了这个
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 包SecretClient
(在 Azure.Security.KeyVault.Secrets
- 用于 keyvault 中定义)完全获取证书(包括
*.pfx
文件中的私有部分)的技巧是 not 使用 client.GetCertificate
调用 - 而是使用 client.GetSecret
调用。 GetCertificate
调用将仅返回证书的公共部分并删除任何私有部分。
要传入的
vaultName
类似于 https://yourcustomname.vault.azure.net
,并且 certName
必须与您在 Azure Keyvault 中为证书提供的名称相匹配。
于 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/