| | | 1 | | <# |
| | | 2 | | .SYNOPSIS |
| | | 3 | | Exports an X509Certificate2 to PFX or PEM(+key). |
| | | 4 | | .DESCRIPTION |
| | | 5 | | This function exports a given X509Certificate2 object to a specified file path in either PFX or PEM format. |
| | | 6 | | If the PEM format is chosen and the IncludePrivateKey switch is set, it will also export the private key. |
| | | 7 | | .PARAMETER Certificate |
| | | 8 | | The X509Certificate2 object to export. |
| | | 9 | | .PARAMETER FilePath |
| | | 10 | | The file path to export the certificate to (without extension). |
| | | 11 | | .PARAMETER Format |
| | | 12 | | The export format (Pfx or Pem). |
| | | 13 | | .PARAMETER Password |
| | | 14 | | The password to protect the exported PFX file (if applicable). |
| | | 15 | | .PARAMETER IncludePrivateKey |
| | | 16 | | Whether to include the private key in the export (only applicable for PEM format). |
| | | 17 | | |
| | | 18 | | .EXAMPLE |
| | | 19 | | Export-KrCertificate -Certificate $cert -FilePath 'C:\certs\my' ` |
| | | 20 | | -Format Pem -Password 'p@ss' -IncludePrivateKey |
| | | 21 | | .NOTES |
| | | 22 | | This function requires the Kestrun module to be imported. |
| | | 23 | | #> |
| | | 24 | | function Export-KrCertificate { |
| | | 25 | | [KestrunRuntimeApi('Everywhere')] |
| | | 26 | | [CmdletBinding()] |
| | | 27 | | param( |
| | | 28 | | [Parameter(Mandatory = $true, ValueFromPipeline = $true)] |
| | | 29 | | [System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate, |
| | | 30 | | |
| | | 31 | | [Parameter(Mandatory = $true)] |
| | | 32 | | [string]$FilePath, |
| | | 33 | | |
| | | 34 | | [Parameter()] |
| | | 35 | | [ValidateSet('Pfx', 'Pem')] |
| | | 36 | | [string]$Format = 'Pfx', |
| | | 37 | | |
| | | 38 | | [Parameter()] |
| | | 39 | | [securestring]$Password, |
| | | 40 | | |
| | | 41 | | [Parameter()] |
| | | 42 | | [switch]$IncludePrivateKey |
| | | 43 | | ) |
| | | 44 | | process { |
| | 0 | 45 | | if ($null -eq $Certificate) { |
| | 0 | 46 | | throw 'Certificate parameter is required.' |
| | | 47 | | } |
| | 0 | 48 | | if ([string]::IsNullOrWhiteSpace($FilePath)) { |
| | 0 | 49 | | throw 'FilePath parameter is required.' |
| | | 50 | | } |
| | 0 | 51 | | $resolvedPath = Resolve-KrPath -Path $FilePath -KestrunRoot |
| | 0 | 52 | | Write-KrLog -Level Verbose -Message "Resolved file path: $resolvedPath" |
| | | 53 | | |
| | 0 | 54 | | $fmtEnum = [Kestrun.Certificates.ExportFormat]::$Format |
| | 0 | 55 | | [Kestrun.Certificates.CertificateManager]::Export($Certificate, $resolvedPath, $fmtEnum, $Password, |
| | | 56 | | $IncludePrivateKey.IsPresent) |
| | 0 | 57 | | Write-KrLog -Level Verbose -Message "Certificate exported to $resolvedPath with format $Format" |
| | | 58 | | } |
| | | 59 | | } |