【问题标题】:Importing Certificate with private key使用私钥导入证书
【发布时间】:2017-11-15 15:24:13
【问题描述】:

我正在尝试使用私钥导入证书,尽管我的脚本正在“工作”,但它缺少一些我似乎无法弄清楚的东西。

我有一个与 KeyVault 对话并使用此证书进行授权的应用程序。我有所述证书的密码,当我手动安装PFX 并分配NETWORK SERVICE 帐户权限时,这工作正常。但是,使用下面的 PowerShell 我得到错误Keyset does not exist。当我在证书管理器下检查时,一切似乎都很正常。显然,用户界面正在做一些不同的事情......有什么想法吗?

编辑 当我手动添加NETWORK SERVICE 帐户时,它工作正常。当我执行脚本时,PowerShell 正在管理员模式下运行,所以这可能有点奇怪?

脚本

cls
$certName = "certname.pfx"
$path = "C:\Certificates\$certName"
$serviceAccount = 'NETWORK SERVICE'
$permissionType = 'Read'
$password = 'somepassword'

try {
    # Import the certificate maintaining the private key format
    $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
    $cert.Import($path, $password, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]"PersistKeySet")

    # Add the cert to personal store location
    $store = Get-Item Cert:\LocalMachine\My
    $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]"ReadWrite")
    $store.Add($cert)
    $store.Close()

    # Get SecurityIdentifier value from current username
    $currentUser = New-Object System.Security.Principal.NTAccount($env:USERNAME)
    $strSID = $currentUser.Translate([System.Security.Principal.SecurityIdentifier])
    $path = "$env:USERPROFILE\AppData\Roaming\Microsoft\Crypto\RSA\$($strSID.Value)\$($cert.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName)"
    $acl = Get-Acl $path
    $rule = New-Object Security.AccessControl.FileSystemAccessRule $serviceAccount, 'FullControl', Allow
    $acl.AddAccessRule($rule)
    Set-Acl $path $acl

    Write-Host "Cert installed, press any key to continue" -ForegroundColor Green
    Read-Host
}
catch {
    Write-Error -Message $_
}

回答 对于遇到与我相同问题的其他人,只需提供多个存储标志:

$flags = @([System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]"MachineKeySet", [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]"PersistKeySet")
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import($path, $password, $flags)

【问题讨论】:

  • 你从哪里得到错误?
  • 当我运行我的应用程序时。该脚本执行良好,但我没有正确添加 NETWORK SERVICE 帐户,因为当我手动执行它时,它会起作用。
  • 是的,但是哪一行/哪一步?
  • 上述脚本运行成功,只有当我尝试使用网络服务帐户运行我的应用程序时,它才会失败并显示错误“密钥集不存在”。

标签: powershell x509certificate pfx


【解决方案1】:

可能想要同时使用PersistKeySetMachineKeySet 导入证书。看看你在这里做事的方式

  • 在不指定 User vs Machine KeySet 的情况下打开 PFX
  • 将其添加到 LocalMachine 商店。
  • 在当前用户的 SID 下找到密钥文件。

Windows 证书存储区 AFAIK 不会记下哪个用户拥有密钥,只是该证书与“用户密钥 {id}”配对。所以它需要是机器(共享)密钥库。

“密钥集不存在”是因为网络服务用户的密钥库中没有以该 ID 命名的密钥。

因此,不同之处可能在于 UI 断言 MachineKeySet(等效),因为它知道您正在导入 LocalMachine 商店。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-17
    • 2019-12-06
    • 1970-01-01
    • 1970-01-01
    • 2013-03-29
    • 1970-01-01
    • 2014-11-26
    • 1970-01-01
    相关资源
    最近更新 更多