使用Powershell获取证书信息

时间:2019-05-10 09:22:36

标签: powershell ssl powershell-core

我的想法是要有一个几乎不作任何更改(例如get-childitem中的路径)的可用于(windows和ubuntu)的powershell代码,所以我在ubuntu上尝试了以下脚本,但在Windows和Windows上不起作用它显示了以下错误

  

openssl.exe:无法打开[主题]

     

第5行char:10

     
      
  • $ var =((&C:\ OpenSSL-Win64 \ bin \ openssl.exe x509 -in $ File -dates -no ...
  •   

这是我编写的代码:

$files = get-childitem Cert:\LocalMachine\My    
foreach ($File in $files) 
{ 
$var = ((& C:\OpenSSL-Win64\bin\openssl.exe x509 -in $File -dates -noout) - 
match 'notAfter')
Write-Host $var
}

另一句话:openssl用来获取证书名称的语法

1 个答案:

答案 0 :(得分:2)

openssl x509 -in期望以文件路径作为参数,而不是[X509Certificate]对象的自定义格式输出。

相反,您可以做的是re-encode the certificate in PEM format(base64)并将其通过管道传输到openssl

if($IsWindows){
    foreach($cert in Get-ChildItem cert:\LocalMachine\My\) {
       # Write BEGIN line
       $certStrings  = @('-----BEGIN CERTIFICATE-----')

       # Export cert data
       $certData     = $cert.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert)

       # Convert to Base64 + append
       $certStrings += [Convert]::ToBase64String($certData, [System.Base64FormattingOptions]::InsertLineBreaks)

       # Write END line
       $certStrings += '-----END CERTIFICATE-----'

       # Pass off to openssl.exe
       $NotAfter = @(($certStrings -join [System.Environment]::NewLine) | .\path\to\openssl.exe x509 -text -noout -dates) -match 'notAfter'

       Write-Host $NotAfter
    }
}
else {
    foreach($cert in Get-ChildItem cert:\LocalMachine\My\) {
        $notAfter = @(& path\to\openssl.exe x509 -in $cert -dates -noout) -match 'notAfter'
Write-Host $notAfter
    }
}