From 5770956533d070bb3aecc69a34a7c05f4ca98067 Mon Sep 17 00:00:00 2001 From: Christian Stein Date: Tue, 24 Mar 2020 11:13:01 +0100 Subject: [PATCH] Add support to create X509 certificates based on .crt/.cert Thanks to @crited --- lib/web/ConvertTo-IcingaX509Certificate.psm1 | 48 ++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 lib/web/ConvertTo-IcingaX509Certificate.psm1 diff --git a/lib/web/ConvertTo-IcingaX509Certificate.psm1 b/lib/web/ConvertTo-IcingaX509Certificate.psm1 new file mode 100644 index 0000000..2bba530 --- /dev/null +++ b/lib/web/ConvertTo-IcingaX509Certificate.psm1 @@ -0,0 +1,48 @@ +function ConvertTo-IcingaX509Certificate() +{ + param( + [string]$CertFile = $null, + [string]$OutFile = $null, + [switch]$Force = $FALSE + ); + + # Use an empty password for converted certificates + $Password = $null; + # Use a target file to specify if we use temp files or not + $TargetFile = $null; + # Temp Cert + [bool]$TempFile = $FALSE; + + # Create a temp file to store the certificate in + if ([string]::IsNullOrEmpty($OutFile)) { + # Create a temporary file for full path and name + $TargetFile = New-IcingaTemporaryFile; + # Get the actual path to work with + $TargetFile = $TargetFile.FullName; + # Set internally that we are using a temp file + $TempFile = $TRUE; + # Delete the file again + Remove-Item $TargetFile -Force -ErrorAction SilentlyContinue; + } + + # Convert our certificate if our target file does not exist + # it is a temp file or we force its creation + if (-Not (Test-Path $TargetFile) -Or $TempFile -Or $Force) { + Write-Output "$Password + $Password" | certutil -mergepfx "$CertFile" "$TargetFile" | Out-Null; + } + + # If no target file exists afterwards (a valid PFX certificate) + # then throw an exception + if (-Not (Test-Path $TargetFile)) { + throw 'The specified/created certificate file could not be found.'; + } + + # Now load the actual certificate from the path + $Certificate = New-Object Security.Cryptography.X509Certificates.X509Certificate2 $TargetFile; + # Delete the PFX-Certificate which will be present after certutil merge + Remove-Item $TargetFile -Force -ErrorAction SilentlyContinue; + + # Return the certificate + return $Certificate +}