VSTS - 如何将从Azure Key Vault检索的客户端证书转换为PowerShell X509Certificate实例

3
为了提供一些背景,我们有一个使用客户端证书身份验证进行安全保护的WebAPI项目。
我们的构建-发布步骤之一是使用Powershell调用我们自己的API,但我们需要添加证书才能使该调用工作。
我们使用下面的任务来检索Azure托管的密钥(实际上是直接在密钥库上生成的自签名证书)。

https://learn.microsoft.com/en-us/vsts/build-release/tasks/deploy/azure-key-vault?view=vsts

这项任务成功返回了证书并将其放在一个变量中,但我们无法将该变量转换为实际的X509Certificate实例,因为根据上面的页面所述,它是一个字符串表示。Invoke-WebRequest期望得到实际的实例。
我们从VSTS发布过程中收到的错误如下:
2018-05-16T19:33:12.2384270Z ##[error]Cannot bind parameter 'Certificate'. Cannot convert value "***" to type "System.Security.Cryptography.X509Certificates.X509Certificate". Error: "The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters."

2018-05-16T19:33:12.2398107Z ##[debug]Processed: ##vso[task.logissue type=error]Cannot bind parameter 'Certificate'. Cannot convert value "***" to type "System.Security.Cryptography.X509Certificates.X509Certificate". Error: "The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters."

2018-05-16T19:33:12.2399696Z ##[debug]Processed: ##vso[task.complete result=Failed]

2018-05-16T19:33:12.2611215Z ##[section]Finishing: Azure PowerShell script: API Validation

此时,我甚至不确定构建从任务中获取的值是什么类型。它是字符串,受保护的字符串还是其他类型?如何将其转换为X509证书?

Invoke-WebRequest文档显示-Certificate开关期望X509证书类型。

[-Certificate <X509Certificate>]

我已经在网上看到了一些代码,展示了如何从密钥保管库中检索证书,但是这是直接使用 Azure CmdLets 检索它并获得字节返回值,而不是像 VSTS 任务那样获取字符串表示形式。
$PFXPath = 'mycert.pfx'
$PFXPassword = ''
$PFX = New-Object -TypeName 'System.Security.Cryptography.X509Certificates.X509Certificate2Collection'
$PFX.Import($PFXPath,$PFXPassword,[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet)
$PFX

说了这么多,有人知道如何将使用VSTS任务检索的证书(返回字符串表示形式)转换为我可以传递给Powershell Invoke-WebRequest调用的单个X509证书实例吗?非常感谢任何帮助,谢谢。

你解决了这个问题吗? - starian chen-MSFT
嗨@starianchen-MSFT,我们正在进行中。实际上,Adriano的解决方案适用于在本地运行代码时。我们遇到的问题是在通过VSTS任务从KeyVault获取证书时。我们将在修复后发布确切的解决方案。 - GR7
1个回答

1
您提供的文档链接(https://learn.microsoft.com/en-us/vsts/build-release/tasks/deploy/azure-key-vault?view=vsts#arguments)似乎回答了您的问题(证书编码为base64字符串):

If the value fetched from the vault is a certificate (for example, a PFX file), the task variable will contain the contents of the PFX in string format. You can use the following PowerShell code to retrieve the PFX file from the task variable:

$kvSecretBytes = [System.Convert]::FromBase64String($(PfxSecret))
$certCollection = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
$certCollection.Import($kvSecretBytes,$null,[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)

谢谢Adriano。你说得对,这段代码在本地运行时是有效的,但不知何故,从VSTS任务返回的值无法正确转换。我们在接下来的几天内解决后,我会再次确认。 - GR7

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接