运行Importpfx.exe导入证书的奇怪结果

时间:2012-09-17 08:27:35

标签: powershell certificate

我正在编写一个Powershell脚本来自动设置Windows 2008 R2服务器,并且需要将一些证书导入到不同的商店。在做了一些关于如何最好地实现这一目标的研究后,我发现Importpfx.exe是我打算做的最佳选择,即将一个.pfx文件导入Trusted People商店,将另一个.pfx文件导入Personal Store。 ,均为计算机帐户。然后,我还需要在导入到个人存储中的证书上管理私钥。

起初,我认为Importpfx.exe正确地执行了此操作,但在研究了如何通过Powershell管理私钥后,我了解到这可以通过编辑与导入的证书对应的文件的acl来完成这应该在这里找到“C:\ ProgramData \ Microsoft \ Crypto \ RSA \ MachineKeys”。这是我开始注意到导入的证书不太正确的地方。在导入证书后搜索此文件夹以获取新文件后,我注意到没有新文件添加到此文件夹中。

我在整个C盘中搜索了按修改日期排序的所有文件,发现新文件已添加到此文件夹“C:\ Users \'user'\ AppData \ Roaming \ Microsoft \ Crypto \ RSA \ S-1 -5-21-2545654756-3424728124-1046164030-4917“而不是预期的文件夹。虽然我能够通过证书存储区手动管理证书的私钥(因为我是导入它的用户),但没有其他用户能够登录到计算机并管理私钥,收到错误消息“无法找到证书和用于解密的私钥“(考虑到相应文件所在的文件夹,这将是有意义的。)

在尝试导入.pfx文件之前,我使用函数来获取证书的指纹。我以前运行的代码是:

function GetCertificateThumbprint ( [string]$certPreFix, [string]$certPassword, [string]$certFolder, [string]$domain, [bool]$addIfNotFound, [hashtable]$return)

$storePath = "cert:\LocalMachine"
$storeDir = "My"
$storeName = [System.Security.Cryptography.X509Certificates.StoreName]::My
if($certPreFix -eq "XXX")
{
    $storeDir = "TrustedPeople"
    $storeName = [System.Security.Cryptography.X509Certificates.StoreName]::TrustedPeople
}
$storePath = [System.IO.Path]::Combine($storePath, $storeDir)
#Build the certificate file name and get the file
$certFileName = $certPreFix + "." + $domainName + ".*"
$certFile = Get-ChildItem -Path $certFolder -Include $certFileName -Recurse
if ($certFile)
{
#   The certificate file exists so get the thumbprint   
    $Certificate = New-Object system.Security.Cryptography.X509Certificates.X509Certificate2($certFile, $certPassword)
    $certThumbprint = $Certificate.Thumbprint
    if($addIfNotFound)
    {
#       Check for the certificate's thumbprint in store and add if it does not exist already    
        if(-not(Get-ChildItem $storePath | Where-Object {$_.Thumbprint -eq $certThumbprint}))
        {
            Set-Location "$Env:windir\Tools"
            .\importpfx.exe -f $certFile -p $certPassword -t MACHINE -s $storeDir
        }
    }
}

有谁能看出我做错了什么?有人遇到过这个问题并以某种方式绕过它吗?这导致了我的问题,因为我无法正确自动执行管理私钥任务!

1 个答案:

答案 0 :(得分:1)

我刚遇到同样的问题。创建证书对象时,必须指定 MachineKeySet X509KeyStorageFlag

New-Object system.Security.Cryptography.X509Certificates.X509Certificate2($certFile, $certPassword, "PersistKeySet,MachineKeySet")

希望这有助于某人。