1

My idea is to have a powershell code that is available for both (windows and ubuntu) with few changes (like the path in get-childitem),so I tried the following script on ubuntu , but did not work on windows and it shows me the following error

openssl.exe : Can't open [Subject]

At line:5 char:10

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

Here is the code that I've wrote:

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

Another remark: what syntaxe to use with openssl to get certificate name

Community
  • 1
  • 1
mamadou
  • 135
  • 2
  • 13
  • Use the same code, but differentiate the platform with the automatic variables `$IsWindows`,`$IsLinux`,`$IsMacOs`. I.e. `if ($IsLinux){"Do Liux stuff"} elseif ($IsMacOS) {"Do OS X stuff"} else {"Do Windws stuff"}` –  May 10 '19 at 09:47

1 Answers1

2

openssl x509 -in expects a file path as it's argument, not the custom formatted output of a [X509Certificate] object.

What you can do instead is re-encode the certificate in PEM format (base64) and pipe that to 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
    }
}
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206