0

我正在编写一个 Powershell 脚本来自动设置 Windows 2008 R2 服务器,而需要做的一件事是将多个证书导入不同的商店。在对如何最好地实现这一点进行了一些研究之后,我发现 Importpfx.exe 是我的目标的最佳选择,即将一个 .pfx 文件导入受信任的人存储,另一个 .pfx 文件导入个人存储, 均适用于计算机帐户。然后,我还需要在导入个人存储后的证书上管理私钥。

起初,我认为 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
        }
    }
}

谁能看看我是否做错了什么?有没有人遇到过这个问题并以某种方式解决它?这引起了我的问题,因为我无法正确自动执行“管理私钥”任务!

4

1 回答 1

1

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

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

希望这可以帮助某人。

于 2013-04-18T04:10:26.787 回答