如何从 Key Vault 获取证书密钥对并将其导入 Windows Server?

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

证书已导入 Azure Key Vault。如何在 Windows Server 上下载并安装它?

问题是手动下载证书时没有密码。

我的问题是:

  • 如何在powershell中从Key Vault下载证书。

  • 下一步(因为我们知道从 Key Vault 下载时的证书 没有关联的密码)如何通过 powershell 将证书安装到 Windows Server 中?激情还是其他?

手动下载证书时不起作用。密码也为空。

一直在使用:

$vaultName = "SomeoneBusiness"
$certificateName = "SomeoneDotcom"
$exportFilePath = "C:\MyCert\YourCertificate.pfx"  # Define export file path including filename and extension
$certificatePassword = "SuperSecret"  # Password used to protect the exported PFX

# Get the certificate from Azure Key Vault
$certificate = Get-AzKeyVaultCertificate -VaultName $vaultName -Name $certificateName

# Export the certificate to a .pfx file with password protection
Export-PfxCertificate -Cert $certificate.Certificate -FilePath $exportFilePath -Password (ConvertTo-SecureString -String $certificatePassword -AsPlainText -Force)

但是它不会下载或创建Certificate.pfx

接下来需要在经典模式下的azure发布管道中放置一个任务,将“certificate.pfx”发布到Windows服务器上并导入。 有想法吗?

我是不是走错方向了?

azure powershell ssl-certificate azure-keyvault
1个回答
0
投票

Get-AzKeyVaultCertificate
永远不会下载私钥;也就是说,您永远不会获得密钥对。此外,导入时必须提供密码。私钥在存储在 Key Vault 中时会使用密码进行解密,因此即使您获得密钥对,私钥也已被解密。您还需要确保证书策略允许导出私钥。默认策略将允许导出,但如果您需要更改它,则必须在导入新版本的证书之前先执行此操作:该策略适用于next版本,或由
Add-AzKeyVaultCertificate
添加的版本(与本例无关,但可能在将来有所帮助)。

为了进行演示,假设您有一个私钥已加密的 PFX (PKCS12) 文件。导入它:

$password = ConvertTo-SecureString -String 'hunter2' -AsPlainText
Import-AzKeyVaultCertificate -VaultName myvault -Name mycert -FilePath mycert.pfx -Password $password

要获取私钥(同样,该私钥已被解密),您需要获取恰好与证书同名的托管机密:

$cert = Get-AzKeyVaultCertificate -VaultName myvault -Name mycert
$cert.Certificate.HasPrivateKey # False

$encoded = Get-AzKeyVaultSecret -VaultName myvault -Name mycert -AsPlainText
$cert2 = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new([Convert]::FromBase64String($encoded))
$cert2.HasPrivateKey # True

请注意,如果在导入证书或在 Key Vault 中创建新证书时未导出私钥,则托管机密将不包含私钥 - 仅包含证书。

如果您希望私钥在导入到本地计算机后可导出(不推荐),请将

X509Certificate2::new
构造函数调用更改为:

$cert2 = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new([Convert]::FromBase64String($encoded), $null, 'Exportable')

如果您想将证书自动安装到计算机存储中,请确保您在提升的进程中运行此脚本,并且可以直接在 PowerShell 中执行此操作,而无需导出到文件:

# Or use a different StoreName below rather than "My" as appropriate.
$store = [System.Security.Cryptography.X509Certificates.X509Store]::new('My', 'LocalMachine', 'ReadWrite,OpenExistingOnly')
$store.Add($cert)
$store.Close()

证书现已导入。

如果您想将其保存到受密码保护的文件中,您可以使用:

$cert.Export('pfx', $password) | Set-Content mycert2.pfx -AsByteStream

然后您可以使用

certmgr.msc
certutil.exe
或任意数量的工具将文件导入到证书存储中。

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