| | 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 | | [Parameter(Mandatory = $true)] |
| | 31 | | [string]$FilePath, |
| | 32 | | [ValidateSet('Pfx', 'Pem')] |
| | 33 | | [string] $Format = 'Pfx', |
| | 34 | | [securestring] $Password, |
| | 35 | | [switch] $IncludePrivateKey |
| | 36 | | ) |
| | 37 | | process { |
| 0 | 38 | | if ($null -eq $Certificate) { |
| 0 | 39 | | throw "Certificate parameter is required." |
| | 40 | | } |
| 0 | 41 | | if ([string]::IsNullOrWhiteSpace($FilePath)) { |
| 0 | 42 | | throw "FilePath parameter is required." |
| | 43 | | } |
| 0 | 44 | | $resolvedPath = Resolve-KrPath -Path $FilePath -KestrunRoot |
| 0 | 45 | | Write-KrLog -Level Verbose -Message "Resolved file path: $resolvedPath" |
| | 46 | |
|
| 0 | 47 | | $fmtEnum = [Kestrun.Certificates.CertificateManager+ExportFormat]::$Format |
| 0 | 48 | | [Kestrun.Certificates.CertificateManager]::Export($Certificate, $resolvedPath, $fmtEnum, $Password, |
| | 49 | | $IncludePrivateKey.IsPresent) |
| 0 | 50 | | Write-KrLog -Level Verbose -Message "Certificate exported to $resolvedPath with format $Format" |
| | 51 | | } |
| | 52 | | } |
| | 53 | |
|