【问题标题】:Get certificates information using powershell使用 powershell 获取证书信息
【发布时间】:2019-05-10 09:22:35
【问题描述】:

我的想法是有一个可用于(windows 和 ubuntu)的 powershell 代码,只需少量更改(如 get-childitem 中的路径),所以我在 ubuntu 上尝试了以下脚本,但在 windows 和它向我显示以下错误

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

在 line: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 使用什么语法来获取证书名称

【问题讨论】:

  • 使用相同的代码,但使用自动变量$IsWindows,$IsLinux,$IsMacOs 区分平台。 IE。 if ($IsLinux){"Do Liux stuff"} elseif ($IsMacOS) {"Do OS X stuff"} else {"Do Windws stuff"}

标签: powershell ssl powershell-core


【解决方案1】:

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
    }
}

【讨论】:

  • 不错的一个。编码到 base 64 的转换非常棒
  • 我在 ubuntu 上试过了,没用,它告诉我“方法调用失败,因为它不包含方法导出”
  • 正如@LotPings 指出的,您可以尝试使用$Is* 自动变量检测平台,更新答案
猜你喜欢
  • 2020-04-30
  • 2018-02-17
  • 1970-01-01
  • 1970-01-01
  • 2016-04-05
  • 2011-12-13
  • 2015-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多