har*_*ang 6 powershell-2.0 x509certificate
我使用以下 PowerShell 函数将 PFX 导入到我的 Windows 2008 R2 服务器的证书存储中
function Import-PfxCertificate ([String]$certPath,[String]$certificateStoreLocation = "CurrentUser",[String]$certificateStoreName = "My",$pfxPassword = $null)
{
$pfx = new-object System.Security.Cryptography.X509Certificates.X509Certificate2
$pfx.Import($certPath, $pfxPassword, "Exportable,PersistKeySet")
$store = new-object System.Security.Cryptography.X509Certificates.X509Store($certificateStoreName,$certificateStoreLocation)
$store.open("MaxAllowed")
$store.add($pfx)
$store.close()
return $pfx
}
Run Code Online (Sandbox Code Playgroud)
该函数的调用者看起来像$importedPfxCert = Import-PfxCertificate $pfxFile "LocalMachine" "My" $password我将它安装到本地机器的我的商店。然后我向我的 IIS 应用程序池授予了读取权限。
我有一个需要使用它的 WCF 服务
<behaviors>
<serviceBehaviors>
<behavior>
<serviceCredentials>
<serviceCertificate findValue="MyCertName" x509FindType="FindBySubjectName" />
<userNameAuthentication userNamePasswordValidationMode="Custom"
customUserNamePasswordValidatorType="MyValidator" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
Run Code Online (Sandbox Code Playgroud)
当我使用客户端调用服务时,WCF 出现异常 It is likely that certificate 'CN=MyCertName' may not have a private key that is capable of key exchange or the process may not have access rights for the private key.
如果我从 MMC 中删除它,并从证书 MMC 手动导入相同的 PFX 文件到同一个存储并授予相同的权限,我的客户可以毫无问题地调用该服务。
所以这让我想到,出于某种原因,如果我使用 PowerShell,私钥会以某种方式被搞砸。
有趣的是,无论哪种方式,我都转到 MMC 并双击我可以看到的已安装证书,You have a private key that corresponds to the certificate.因此看起来即使在 PowerShell 中也加载了私钥。权限设置相同。
任何线索或经验?
有同样的问题。下一个脚本工作:
function InstallCert ($certPath, [System.Security.Cryptography.X509Certificates.StoreName] $storeName)
{
[Reflection.Assembly]::Load("System.Security, Version=2.0.0.0, Culture=Neutral, PublicKeyToken=b03f5f7f11d50a3a")
$flags = [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::MachineKeySet -bor [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($certPath, "", $flags)
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store($storeName, [System.Security.Cryptography.X509Certificates.StoreLocation]::LocalMachine)
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite);
$store.Add($cert);
$store.Close();
}
Run Code Online (Sandbox Code Playgroud)