我希望在证书的现有指纹与网站匹配时导入 SSL 证书

我希望在证书的现有指纹与网站匹配时导入 SSL 证书

我编写了一个 PS 脚本,其中它将证书导入到现有站点的 IIS 服务器,但我想要一个脚本,其中它将我拥有的证书的指纹与本地机器存储中的证书的指纹进行匹配,如果指纹匹配则将该证书导入存储,如果不匹配则不导入该证书。

例子 我有一个带有指纹 = XXXXXX 的 pfx 文件,并且需要检查脚本,看看我的计算机或任何远程服务器中是否有与上述相同的指纹,然后我需要替换或导入我拥有的证书到该位置。

代码

#Clearing the Console host in PS
Clear-Host

$certPath = 'C:\TEMP\Sample.pfx'
$CertificatePassword = 'XXXXXX'
$SiteName = "SampleTest"
$HostName = "Sitebinding.com"
$SiteFolder = Join-Path -Path 'C:\inetpub\wwwroot' -ChildPath $SiteName


Write-Host 'Import pfx certificate' $certPath
$certRootStore = “LocalMachine”
$certStore = "My"
$pfx = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$pfx.Import($certPath,$CertificatePassword,"Exportable,PersistKeySet") 
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store($certStore,$certRootStore) 
$store.Open('ReadWrite')
$store.Add($pfx) 
$store.Close() 
$certThumbprint = $pfx.Thumbprint


#Write-Host 'Add website' $SiteName
#New-WebSite -Name $SiteName -PhysicalPath $SiteFolder -Force
#$IISSite = "IIS:\Sites\$SiteName"
#Set-ItemProperty $IISSite -name  Bindings -value @{protocol="https";bindingInformation="*:443:$HostName"}
#if($applicationPool) { Set-ItemProperty $IISSite -name  ApplicationPool -value $applicationPool}


Write-Host 'Bind certificate with Thumbprint' $certThumbprint
#$obj = get-webconfiguration "//sites/site[@name='$SiteName']"
$obj = Get-WebBinding $SiteName -Port 443
#$binding = $obj.bindings.Collection[0]
#$method = $binding.Methods["AddSslCertificate"]
$method = $obj.Methods["AddSslCertificate"]
$methodInstance = $method.CreateInstance()
$methodInstance.Input.SetAttributeValue("certificateHash", $certThumbprint)
$methodInstance.Input.SetAttributeValue("certificateStoreName", $certStore)
$methodInstance.Execute()```

Thanks In Advance.

答案1

要获取本地计算机个人存储中的证书列表:

$localcerts = Get-ChildItem Cert:\LocalMachine\My

要获取 pfx 的证书对象(我的有一个密码):

$cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new("C:\temp\mypfx.pfx","mypassword", [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::MachineKeySet)

比较指纹:

if ($localcerts.Thumbprint -contains $cert.Thumbprint) { <# do stuff #> }

如果您要在本地电脑上搜索其他商店(如受信任的发布者),请通过根目录进行递归:

$localcerts = Get-ChildItem cert:\LocalMachine -recurse
$localcerts.thumbprint  # Returns 130+ certificates on my machine

相关内容