Azure Key Vault 下载带有私钥的证书

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

我正在尝试下载多个 KeyVault 上的证书,包括它们的私钥。通过 Azure 门户,我可以毫无问题地完成此操作,只需转到 KeyVault,选择 证书,然后单击 “以 PFX/PEM 格式下载”

由于我必须在多个密钥库上重复相同的操作,因此我一直在寻找一种自动化的方法来完成此操作。到目前为止,我得出以下结论:

$objCertificate = (Get-AzKeyVaultCertificate -VaultName <Key Vault> -Name <Certificate Name>).Certificate
$bytCertificate = $objCertificate.Export('pfx',<Password>)
$strCertificate = [System.Convert]::ToBase64String($bytCertificate)
$strPath = Join-Path $env:TEMP "$($objCertificate.Subject).pfx"
$bytCertificate | Set-Content -Path $strPath -Force -Encoding Byte

问题是它仅使用公钥下载证书,我还需要其中包含私钥,就像我通过门户下载证书时一样。 你知道我可能会错过什么吗?

powershell certificate azure-keyvault
4个回答
10
投票

要获取私钥,您需要将其作为秘密获取(是的,这很奇怪),我在 PowerShell 中没有答案,但我希望下面的 C# 代码可以为您提供一些有关如何执行此操作的提示。

        /// <summary>
        /// Load a certificate (with private key) from Azure Key Vault
        ///
        /// Getting a certificate with private key is a bit of a pain, but the code below solves it.
        /// 
        /// Get the private key for Key Vault certificate
        /// https://github.com/heaths/azsdk-sample-getcert
        /// 
        /// See also these GitHub issues: 
        /// https://github.com/Azure/azure-sdk-for-net/issues/12742
        /// https://github.com/Azure/azure-sdk-for-net/issues/12083
        /// </summary>
        /// <param name="config"></param>
        /// <param name="certificateName"></param>
        /// <returns></returns>
        public static X509Certificate2 LoadCertificate(IConfiguration config, string certificateName)
        {
            string vaultUrl = config["Vault:Url"] ?? "";
            string clientId = config["Vault:ClientId"] ?? "";
            string tenantId = config["Vault:TenantId"] ?? "";
            string secret = config["Vault:Secret"] ?? "";

            Console.WriteLine($"Loading certificate '{certificateName}' from Azure Key Vault");

            var credentials = new ClientSecretCredential(tenantId: tenantId, clientId: clientId, clientSecret: secret);
            var certClient = new CertificateClient(new Uri(vaultUrl), credentials);
            var secretClient = new SecretClient(new Uri(vaultUrl), credentials);

            var cert = GetCertificateAsync(certClient, secretClient, certificateName);

            Console.WriteLine("Certificate loaded");
            return cert;
        }


        /// <summary>
        /// Helper method to get a certificate
        /// 
        /// Source https://github.com/heaths/azsdk-sample-getcert/blob/master/Program.cs
        /// </summary>
        /// <param name="certificateClient"></param>
        /// <param name="secretClient"></param>
        /// <param name="certificateName"></param>
        /// <returns></returns>
        private static X509Certificate2 GetCertificateAsync(CertificateClient certificateClient,
                                                                SecretClient secretClient,
                                                                string certificateName)
        {

            KeyVaultCertificateWithPolicy certificate = certificateClient.GetCertificate(certificateName);

            // Return a certificate with only the public key if the private key is not exportable.
            if (certificate.Policy?.Exportable != true)
            {
                return new X509Certificate2(certificate.Cer);
            }

            // Parse the secret ID and version to retrieve the private key.
            string[] segments = certificate.SecretId.AbsolutePath.Split('/', StringSplitOptions.RemoveEmptyEntries);
            if (segments.Length != 3)
            {
                throw new InvalidOperationException($"Number of segments is incorrect: {segments.Length}, URI: {certificate.SecretId}");
            }

            string secretName = segments[1];
            string secretVersion = segments[2];

            KeyVaultSecret secret = secretClient.GetSecret(secretName, secretVersion);

            // For PEM, you'll need to extract the base64-encoded message body.
            // .NET 5.0 preview introduces the System.Security.Cryptography.PemEncoding class to make this easier.
            if ("application/x-pkcs12".Equals(secret.Properties.ContentType, StringComparison.InvariantCultureIgnoreCase))
            {
                byte[] pfx = Convert.FromBase64String(secret.Value);
                return new X509Certificate2(pfx);
            }

            throw new NotSupportedException($"Only PKCS#12 is supported. Found Content-Type: {secret.Properties.ContentType}");
        }
    }
}

2
投票

您必须将证书作为秘密下载,而不是作为证书。来自 https://azidentity.azurewebsites.net/post/2018/05/17/azure-key-vault-app-service-certificates-finding-downloading-and-converting

Connect-AzAccount

$vaultName  = "<NameOfKeyVault>"
$keyVaultSecretName = "<NameOfTheSecretWhereCertificateIsStored>"

$secret = Get-AzureKeyVaultSecret -VaultName $VaultName -Name $keyVaultSecretName

$pfxCertObject = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList @([Convert]::FromBase64String($secret.SecretValueText),"",[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)

$pfxPassword = -join ((65..90) + (97..122) + (48..57) | Get-Random -Count 50 | % {[char]$_})

$currentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath
[Environment]::CurrentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath
[io.file]::WriteAllBytes(".\KeyVaultCertificate.pfx", $pfxCertObject.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12, $pfxPassword))

Write-Host "Created an App Service Certificate copy at: $currentDirectory\KeyVaultCertificate.pfx"
Write-Warning "For security reasons, do not store the PFX password. Use it directly from the console as required."
Write-Host "PFX password: $pfxPassword" 

0
投票

感谢托雷提供的例子!

为了将来参考,您的代码示例存在问题,您提到了 PEM,但使用了 Psk12。我认为应该是这样的:

if (secret.Properties.ContentType.Equals(CertificateContentType.Pkcs12.ToString(), StringComparison.InvariantCultureIgnoreCase))
{
  return Convert.FromBase64String(secret.Value);
}

// For PEM, we need to extract the base64-encoded message body.
if (secret.Properties.ContentType.Equals(CertificateContentType.Pem.ToString(), StringComparison.InvariantCultureIgnoreCase))
{
  return Convert.FromBase64String(secret.Value);
}

0
投票

如果您不关心保存的 PFX 文件是否有密码,则无需从秘密字符串创建必要的 X509Certificate 并将其导出,您可以简单地使用如下内容:

$certBase64 = Get-AzKeyVaultSecret -VaultName $keyvaultname -Name $secretName -Version $version -AsPlainText
$certBytes = [Convert]::FromBase64String($certBase64)
[System.IO.File]::WriteAllBytes($pfxPath, $certBytes)
© www.soinside.com 2019 - 2024. All rights reserved.