2017-05-05 117 views
0

我正在使用強大的shell腳本來導出包含私鑰的證書,該私鑰還包括路徑中的所有證書。我爲此編寫了一個腳本,它不包括路徑中的證書或根證書。以下是腳本。請告訴我,如果在我的腳本中有任何更改。 在此先感謝。使用私有密鑰(包括使用powershell的路徑中的所有證書)導出證書

$Password="@de08nt2128"; #password to access certificate after expting 
$CertName="WMSvc-WIN-9KC7DG31JBV"; # name of the certificate to export 
$RootCertName="WMSvc-WIN-9KC7DG31JBV"; # root certificate 

$DestCertName="testcert" 
$ExportPathRoot="C:\DestinationFolder" 

$CertListToExport=Get-ChildItem -Path cert:\LocalMachine\My | ?{ $_.Subject -Like "*CN=$CertName*" -and $_.Issuer -eq "CN=$RootCertName" } 

foreach($CertToExport in $CertListToExport | Sort-Object Subject) 
{ 
    $DestCertName=$CertToExport.Subject.ToString().Replace("CN=",""); 

    $CertDestPath=Join-Path -Path $ExportPathRoot -ChildPath "$DestCertName.pfx" 

    $type = [System.Security.Cryptography.X509Certificates.X509Certificate]::pfx 
    $SecurePassword = ConvertTo-SecureString -String $Password -Force –AsPlainText 

    $bytes = $CertToExport.export($type, $SecurePassword) 
    [System.IO.File]::WriteAllBytes($CertDestPath, $bytes) 

} 
"Completed" 

回答

0

Udpated腳本出口的所有證書匹配特定名稱和發行人(與私有密鑰一起)。請確保您以管理員特權時

# Script to export certificate from LocalMachine store along with private key 
$Password = "@de08nt2128"; #password to access certificate after expting 
$CertName = "WMSvc-WIN-9KC7DG31JBV"; # name of the certificate to export 
$RootCertName = "WMSvc-WIN-9KC7DG31JBV"; # root certificate (the Issuer) 
$ExportPathRoot = "C:\DestinationFolder" 

$CertListToExport = Get-ChildItem -Path cert:\LocalMachine\My | ?{ $_.Subject -Like "*CN=$CertName*" -and $_.Issuer -Like "CN=$RootCertName*" } 

foreach($CertToExport in $CertListToExport | Sort-Object Subject) 
{ 
    # Destination Certificate Name should be CN. 
    # Since subject contains CN, OU and other information, 
    # extract only upto the next comma (,) 
    $DestCertName=$CertToExport.Subject.ToString().Replace("CN=",""); 
    $DestCertName = $DestCertName.Substring(0, $DestCertName.IndexOf(",")); 

    $CertDestPath = Join-Path -Path $ExportPathRoot -ChildPath "$DestCertName.pfx" 

    $SecurePassword = ConvertTo-SecureString -String $Password -Force –AsPlainText 

    # Export PFX certificate along with private key 
    Export-PfxCertificate -Cert $CertToExport -FilePath $CertDestPath -Password $SecurePassword -Verbose 
} 

更新您的紙條

  • 運行這個對於檢查$_.Issuer -eq "CN=$RootCertName"工作,你將不得不包括OU,O,S的信息,以及因此它才能正常工作所以我修改它是$_.Issuer -Like "CN=$RootCertName*"以便它匹配所有發行人的是誰的名字帶有可變$RootCertName
  • 使用$CertToExport.Subject.ToString().Replace("CN=","")生成PFX文件名開頭會導致名稱是以下格式some-cert-name, OU=sometext, O=org, C=country.pfx所以最好限制UPTØ下一個逗號(,)所以我加了$DestCertName.Substring(0, $DestCertName.IndexOf(","))
  • 最後使用Export-PfxCertifcate與私鑰
出口