ps/Modules/Alkami.DevOps.Certificates/Private/Export-CertificateToFileSystem.ps1
2023-05-30 22:51:22 -07:00

48 lines
1.8 KiB
PowerShell

function Export-CertificateToFileSystem {
<#
.SYNOPSIS
Exports a Certificate to a Store.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $True)]
[ValidateNotNull()]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Cert,
[Parameter(Mandatory = $True)]
[ValidateNotNull()]
[string]$ExportStorePath,
[bool]$IsChainExport = $false,
[string[]]$ADGroups
)
$certName = Get-CertificateExportName $cert
$exportCertPath = if ($IsChainExport) {$exportStorePath}else {Join-Path $exportStorePath $certName}
$exportInfo = Get-CertificateExportInfo $cert $exportCertPath
if ($exportInfo.certExportType -eq [System.Security.Cryptography.X509Certificates.X509ContentType]::Unknown) {return $null}
if (-Not (Test-Path $exportCertPath -PathType Container)) {
New-Item $exportCertPath -ItemType Directory | Out-Null
}
$exportInfo.certName = $certName
$exportInfo.certPassword = ([char[]]([char]33..[char]95) + ([char[]]([char]97..[char]126)) + 0..9 | Sort-Object {Get-Random})[0..128] -join ''
$exportInfo.ADGroups = $ADGroups
if ($exportInfo.certExportType -eq [System.Security.Cryptography.X509Certificates.X509ContentType]::Pfx) {
$password = $exportInfo.certPassword | ConvertTo-SecureString -AsPlainText -Force
try {
Export-PfxCertificate -Cert $cert -ProtectTo $ADGroups -FilePath $exportInfo.exportCertFile -Password $password
}
catch {
Write-Warning "Certificate $certName with thumbprint $($cert.Thumbprint) but could not be exported
$($_.Exception.Message)"
return $null
}
}
else {
$certBytes = $cert.Export($exportInfo.certExportType)
[void][io.file]::WriteAllBytes($exportInfo.exportCertFile, $certBytes)
}
return $exportInfo
}