通过PS脚本导入的证书已损坏私钥



我在Azure DevOps中运行CI集成测试,运行发生在安装了生成代理的专用Azure VM上。这些测试要求在该 VM 上安装客户端 SSL 证书。作为 CI 中的生成步骤,我有一个 PS 脚本,该脚本使用 Azure 密钥保管库证书并将其导入到本地计算机/我的 VM 存储中。导入证书并且我可以在 VM 中看到它时,来自 CI 的测试使用该证书失败。请注意,尝试在 VM 中手动导出时,证书的"使用私钥导出"选项灰显。

当我在虚拟机中手动运行相同的 PS 脚本,然后运行 CI 测试(禁用 PS 步骤)时,测试成功使用者证书并通过。

我应该在下面的 PS 脚本中更改什么,以便它(远程运行)将导入启用了"使用私钥导出"选项的证书?

$vaultName = "MyKeyVault-stest"
$secretName = "MyCertificate"
$kvSecret = Get-AzureKeyVaultSecret -VaultName $vaultName -Name $secretName
$kvSecretBytes = [System.Convert]::FromBase64String($kvSecret.SecretValueText)
$kvSecretPass = 'myPass'
#-----------------------------------------------------------------------------

$pfxCertObject=New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList @($kvSecretBytes, "", [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
$newcertbytes = $pfxCertObject.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12, $kvSecretPass)
$newCert=New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$newCert.Import($newcertbytes,$kvSecretPass,[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
#-------------------------------------------------------------------------------
$certStore = Get-Item "Cert:LocalMachineMy"
$openFlags = [System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite
$certStore.Open($openFlags) 
$certStore.Add($newCert) 
Write-host $env:USERNAME
Write-host $(whoami)

如果要导入 PFX 以将其添加到持久存储,则需要指定 X509KeyStorageFlags.PersistKeySet 标志。 如果你不这样做,在以后的某个不确定的点,垃圾回收器注意到没有人关心密钥,然后要求Windows删除它......然后添加到 X509Store 的版本无法再找到其密钥。

其他阅读:

  • 在 C# 中导入证书时,"PersistKeySet"-StorageFlag 有什么影响
  • 所有不同的 X509KeyStorageFlag 的基本原理是什么?

最新更新