使用私钥导入证书

时间:2017-11-15 15:24:13

标签: powershell x509certificate pfx

我正在尝试使用私钥导入证书,虽然我的脚本是"工作"它遗漏了我似乎无法弄清楚的东西。

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

修改的 当我手动添加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 $_
}

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

$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)

1 个答案:

答案 0 :(得分:2)

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

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

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

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

因此,差异可能是UI正在声明MachineKeySet(等效),因为它知道您正在导入LocalMachine商店。