A regular expression to match a certificate in a CRT file

I have made a regular expression that matches a text block belonging to a single certificate in a CRT file. This can be tested at https://regex101.com/.

For usage of the expression in powershell, I refer to my previous post Save a sorted CRT file. Take a look in the script and look for $2 , $3 and $4 :

  • $2 is used to catch the ’subject’.
  • $3 is used to catch the ’issuer’.
  • $4 is used to catch the encoded certificate part enclosed in between -----BEGIN CERTIFICATE-----  and -----END CERTIFICATE----- .

Here is the regular expression:

 

Break down of the regular expression

I used CoPilot i Edge to help me out with the break down of the regular expression.

In summary, this regex is designed to extract information related to the subject, issuer, and the actual certificate content from a text block that includes certificate details. It’s used in my PowerShell script to parse the contents of the .crt  file.

Let’s break down the regular expression step by step:

  1. Bag Attributes(\s*|.*)* :
    • This part matches the literal string “Bag Attributes” followed by any number of spaces ( \s* ) or any character ( .* ). The *  quantifier means zero or more occurrences.
    • Essentially, it captures any content that appears before the actual certificate details.
  2. subject=(.*)\sissuer=(.*) (This part captures the subject and issuer attributes of the certificate):
    • subject=(.*)  matches the literal string “subject=” followed by any characters (captured by .* ).
    • \sissuer=(.*)  matches a space followed by the literal string “issuer=” and captures any characters after it.
  3. \s([-]*BEGIN CERTIFICATE[-]*\s(([A-Za-z0-9+\/]{4})*([A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=|[A-Za-z0-9+\/]{4})|\s)+\s[-]*END CERTIFICATE[-]*) (This part captures the actual certificate content, including the “BEGIN CERTIFICATE” and “END CERTIFICATE” markers):
    • \s  matches a space.
    • ([-]*BEGIN CERTIFICATE[-]*  captures the literal string “BEGIN CERTIFICATE” (with optional hyphens).
    • (([A-Za-z0-9+\/]{4})*([A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=|[A-Za-z0-9+\/]{4})|\s)+ described in detail below.
    • Finally, it captures the literal string “END CERTIFICATE” (with optional hyphens) after the certificate content.

Encoded certificate part

This regular expression captures base64-encoded strings (with optional padding) or whitespace. It’s commonly used to extract base64-encoded data from text or to validate base64 strings.

Here is a break down:

  1. ([A-Za-z0-9+\/]{4})* :
    • This part captures groups of four characters (which can be letters, digits, or specific symbols like +  or / ).
    • The *  quantifier means zero or more occurrences of these groups.
  2. ([A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=|[A-Za-z0-9+\/]{4}) :
    • This part captures three different possibilities for the last group of characters in the base64-encoded string:
      • [A-Za-z0-9+\/]{2}== : Two characters followed by == .
      • [A-Za-z0-9+\/]{3}= : Three characters followed by = .
      • [A-Za-z0-9+\/]{4} : Four characters without any additional symbols.
  3. |\s :
    • The |  (pipe) symbol acts as an OR operator.
    • It allows for an alternative match: either the base64-encoded string as described above or a single whitespace character ( \s ).
  4. + :
    • The +  quantifier means one or more occurrences of the entire preceding group (either base64-encoded characters or whitespace).

 

Save a sorted CRT file

While using a Let’s Encrypt certificate exported to a .CRT file, I encountered an error stating, ”Server sent unsorted certificate chain in violation of the TLS specification,” upon connecting to my Filezilla FTP Server. To resolve this, I crafted a function that reorders the original file and saves it with the correct certificate chain sequence.

  1. Read the CRT File:
    • Use Get-Content -Path $OriginalCRTFilepath -Raw  to read the raw content of the .crt  file into a single string.
  2. Regex Pattern Matching:
    • The $regexPattern  defines a regular expression to match individual certificate blocks within the file. It captures attributes like subject, issuer, and the certificate itself.
  3. Finding the Root CA Certificate:
    • Identify the root CA certificate by comparing the subject and issuer fields. If they match, it’s the root certificate.
  4. Finding the Intermediate CA Certificate:
    • The intermediate CA certificate is identified based on the fact that it’s issued by the root CA certificate. You exclude any matches where the subject and issuer are the same (since the root CA certificate is self-issued).
  5. Identifying the End-Entity Certificate (Certificate):
    • The end-entity certificate (your actual certificate) is identified based on the fact that it’s issued by the intermediate CA certificate.
  6. Rename the Original CRT File:

    • Move the original file to $unSortedCRTFilePath filepath.
  7. Saving the Sorted CRT File:
    • Concatenate the certificates in the desired order (certificate, intermediate, root) and save them to the Original filepath $OriginalCRTFilepath .

 

Custom Message Box with XAML transparent GUI

This is a transparent able version of my previous Message Box. It’s based on the first version but with additional features to support GUI transparity. I decided to split them apart since the previous post got to long and it got increasingly more difficult to tell the two apart. I will most likly write separate post for how to use them later.

Below is the Powershell code:

 

Simple Flowdox / Xaml Editor

Working on my other Powershell GUI for displaying a customized MessageBox I wanted to use a RichTextBox control to display the message body. This control takes a Flowdocument (Xaml) as input, enabling messages to be customized with styling like Bold, Italic, Underline, Bullet list, Numbered list and even make selected part mono-spaced. This tool is made to simplify the creation of the Xaml string that can be saved as a text string in the powershell script utilizing the MessageBox. Here’s the script for my take on a Flowdokument editor:

I don’t want to depend of multiple files saved alongside the script to be able to use images in the script so I am saving Base64 encoded images in script. To create these string I used commands as follows:

 

Custom Message Box with XAML GUI

Either save to separate powershell script file och copy paste to the script where you want to run it.

Here is the code for Show-MyMsgBox:

Show popup with System Boot Time (Powershell XAML GUI)

This is a Powershell script that display a popup showing when Computer was last booted. Popup looks like picture below.

Copy the code below to a powershell file, in this example:
”C:\PSTools\SystemBootTime.ps1”.

In the same directory create a shortcut of the file. Open the properties for the shortcut and replace the target path with:

Ensure that the ”Start in:” path is ”C:\PSTools”.

If you want you can change the icon on the shortcut to reflect that it’s a powershell script. Copy the full path to the powershell executable:

then click the ”Change Icon…” button and in the ”Look for icons in this file:” paste the path,  press enter, select the first icon and then klick on ”OK”.

Save the changed to the shortcut.

This is all, to run the script simply doubleklick the shortcut.

 

Active Directory Lost and Found Restore Tool (Powershell XAML GUI)

This is a PowerShell XAML GUI tool that on startup fetches all deleted objects from Active Directory and presents them in a list. From the list one or more objects can be selected and restored by a click on a button.

Theres to parts to the tool. First is the powershell (.ps1) file containing the logic and second there’s a .xaml file containing the xaml code for the GUI.

ADLostAndFoundRestoreTool.ps1

 

ADLostAndFoundRestoreTool.xaml

 

Generate Random Password (Powershell XAML GUI)

Save code below in file: GenerateRandomPassword.ps1

Save code below in file: GenerateRandomPassword.xaml

 

Skript för att uppdatera DynDNS

Detta skript uppdaterar angivna värdnamn i DynDNS.

 

Exportera Certifikat i ’Windows certificate store’ till PFX, CRT och KEY

https://www.thesecmaster.com/procedure-to-install-openssl-on-the-windows-platform/

https://slproweb.com/download/Win64OpenSSL_Light-3_0_1.msi
Export-PfxCertificate
Extracting Certificate and Private Key Files from a .pfx File

Extract certificate to PFX then to CRT and KEY

Detta skript hämtar certifikat där Subject innehåller det som skickats med som argument. Resultatet sorteras på slutdatum och det certifikatet med senaste slutdatum väljs. Detta är det första utkastet jag skrev och skriptet har sina begränsningar då det inte tar höjd för certifikat med multipla DNS-namn. Detta skript körs i powershell kommandorad.

Detta skript är en vidareutveckling av skriptet ovan. Här extraherar vi namnet från FriendlyName. Detta används sedan för namning av skapade filer. Detta skript körs i powershell kommandorad.

GUI

Ovanstående skript är konstruerat för att köras från en Powershell kommandorad. Följande skript består av två filer. En CertExp.XAML-fil som innehåller WPF XAML kod som beskriver uppbyggnaden av gränsnittet. Denna tas fram genom att skapa ett WPF-projekt i Visual Studio och där bygga upp gräsnittet så som det önskas. Efter att man är nöjd (detta är givetvis en iterativ process, sällan man träffar rätt på första försöket) så kopierar man ut XAML-koden från projektet och detta kan antingen sparas inline i powershell-skriptet eller som jag valt här i en egen fil. Nästa fil är själva powershell-skriptet där man först laddar XAML-koden från tidigare nämd fil och sedan fyller man på med den logik som önskas.

I samma mapp som CertExp.ps1 och CertExp.xaml (se nedan) så läggs två D´LL-filer samt en EXE-fil  för OpenSSL, dessa finns att ladda ner i länk nedan.

OpenSSL v3 ZIP ( Direktlänk )
OpenSSL nerladdning (Starsida)

CertExp.XAML

CertExp.ps1