微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从 Az Key Vault 检索证书的私钥以在正确的状态下使用?

如何解决如何从 Az Key Vault 检索证书的私钥以在正确的状态下使用?

我正在尝试使用此 documentation article 中 Powershell 示例中注明的前几行,从生成并存储在 Azure Key Vault 中的证书中检索私钥。我已确保为证书记录启用导出私钥。

我在函数内使用 Connect-AzAccount -Identity 对 Azure 进行身份验证。但是,当我使用有效的 Get-AzkeyvaultCertificate-VaultName 调用 -Vault 时,我收到以下错误

ERROR: Key not valid for use in specified state.
Exception             :Type       :
Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicExceptionTargetSite :Name          : ProtectOrUnprotectDeclaringType : 
System.Security.Cryptography.ProtectedDataMemberType    : MethodModule        : System.Security.Cryptography.ProtectedData.dllStackTrace :at 
..........

我已在 keyvault 上设置了 RBAC 权限,并将 Key Vaults Secret User 角色分配给 Function App。

我需要做什么才能使 Key Vault 机密处于正确的“指定状态”以供使用?

请注意,如果我忽略此错误,似乎我可以在传递给 Connect-MgGraph 时成功使用私钥进行身份验证。出于这个原因,我不相信这个错误实际上是一个功能问题的迹象,但它仍然意味着 Az Func 失败。以下代码是该函数的摘录,以表明其用途。但是,我确实收到了 Get-AzkeyvaultSecretGet-AzkeyvaultCertificate cmdlet 的错误,因此这似乎是一个较低级别的问题:

$certValue = (Get-AzkeyvaultSecret -VaultName "<VAULTNAME>" -Name "<CERTNAME>").SecretValue | ConvertFrom-securestring -AsPlainText
$pfxCert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList @([Convert]::FromBase64String($certValue),"",[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
...
Connect-MgGraph -ClientId $client_id -TenantId $tenantId -Certificate $pfxCert

解决方法

在第一个代码片段中,您获取证书作为证书。使用此方法时,Key Vault 不会返回证书的私钥。

在第二个代码片段(有效)中,您以 base-64 编码状态获取整个证书作为秘密,其中包括私钥。然后代码将其转换为 X509 证书以供使用。

您应该遵循第二种方法。我写了一篇关于这个的博客: https://azidentity.azurewebsites.net/post/2018/07/03/azure-key-vault-certificates-are-secrets

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。