Skip to content

Instantly share code, notes, and snippets.

@Wind010
Last active February 8, 2023 23:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Wind010/c5a6809147f56ac8d2039c01fd50cdc1 to your computer and use it in GitHub Desktop.
Save Wind010/c5a6809147f56ac8d2039c01fd50cdc1 to your computer and use it in GitHub Desktop.
Format oneline PEM private key to multiline format.
param(
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$false)]
[string]
$privateKey,
[Parameter(Mandatory=$false, Position=1, ValueFromPipeline=$false)]
[string]
$delim = "\r\n"
)
#Set-PSDebug -Trace 1
$header="-----BEGIN PRIVATE KEY-----"
$footer="-----END PRIVATE KEY-----"
$charPerLine = 64
$newLineCount = [math]::Ceiling($privateKey.Length/$charPerLine) + 1
$privateKeyFormatted = $privateKey
$arr = @(1..$newLineCount)
# Character limit of 100
#$pattern = "(\w{" + $newLineCount + "})"
#$privateKey -split $pattern | ? {$_}
$prev = 0
$cur = ($charPerLine - 1)
$keyArr = @($null) * $newLineCount
foreach ($i in $arr) {
if ($i -eq $newLineCount-1) {
$keyArr[$i] = $privateKey.Substring($prev, $privateKey.Length - $prev)
break
}
$keyArr[$i] = $privateKey.Substring($prev, $charPerLine)
$prev = $cur
$cur += $charPerLine
}
$privateKeyFormatted = $header
$privateKeyFormatted += $keyArr -join $delim
$privateKeyFormatted += $delim + $footer
$privateKeyFormatted
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment