这是我解决这个问题的方法。首先,将您的 PFX 文件转换为 base64 字符串。您可以使用以下两个简单的 PowerShell 命令来执行此操作:
$fileContentBytes = get-content 'certificate.pfx' -Encoding Byte
[System.Convert]::ToBase64String($fileContentBytes) | Out-File 'certificate_base64.txt'
通过Azure 门户在 Azure Key Vault 中创建机密。复制您之前创建的证书 base64 字符串,并通过Azure 门户将其粘贴到 Azure Key Vault 的密钥值字段中。然后只需从代码中调用 Azure Key Vault 以获取 base64 字符串值并将其转换为X509Certificate2
:
private async Task<X509Certificate2> GetCertificateAsync()
{
var azureServiceTokenProvider = new AzureServiceTokenProvider();
var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
var secret = await keyVaultClient.GetSecretAsync("https://path/to/key/vault").ConfigureAwait(false);
var pfxBase64 = secret.Value;
var bytes = Convert.FromBase64String(pfxBase64);
var coll = new X509Certificate2Collection();
coll.Import(bytes, "certificatePassword", X509KeyStorageFlags.Exportable);
return coll[0];
}