-
Notifications
You must be signed in to change notification settings - Fork 1
Description
Describe the change
If not already supported, add the following functionality to the module:
function ConvertFrom-Base64UrlString {
<#
.SYNOPSIS
Base64url decoder.
.DESCRIPTION
Decodes base64url-encoded string to the original string or byte array.
.PARAMETER Base64UrlString
Specifies the encoded input. Mandatory string.
.PARAMETER AsByteArray
Optional switch. If specified, outputs byte array instead of string.
.INPUTS
You can pipe the string input to ConvertFrom-Base64UrlString.
.OUTPUTS
ConvertFrom-Base64UrlString returns decoded string by default, or the bytes if -AsByteArray is used.
.EXAMPLE
PS Variable:> 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9' | ConvertFrom-Base64UrlString
{"alg":"RS256","typ":"JWT"}
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$Base64UrlString,
[Parameter(Mandatory=$false)][switch]$AsByteArray
)
$s = $Base64UrlString.replace('-','+').replace('_','/')
switch ($s.Length % 4) {
0 { $s = $s }
1 { $s = $s.Substring(0,$s.Length-1) }
2 { $s = $s + "==" }
3 { $s = $s + "=" }
}
if ($AsByteArray) {
return [Convert]::FromBase64String($s) # Returning byte array - convert to string by using [System.Text.Encoding]::{{UTF8|Unicode|ASCII}}.GetString($s)
}
else {
return [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($s))
}
}
function ConvertTo-Base64UrlString {
<#
.SYNOPSIS
Base64url encoder.
.DESCRIPTION
Encodes a string or byte array to base64url-encoded string.
.PARAMETER in
Specifies the input. Must be string, or byte array.
.INPUTS
You can pipe the string input to ConvertTo-Base64UrlString.
.OUTPUTS
ConvertTo-Base64UrlString returns the encoded string by default.
.EXAMPLE
PS Variable:> '{"alg":"RS256","typ":"JWT"}' | ConvertTo-Base64UrlString
eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]$in
)
if ($in -is [string]) {
return [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($in)) -replace '+','-' -replace '/','' -replace '='
}
elseif ($in -is [byte[]]) {
return [Convert]::ToBase64String($in) -replace '+','-' -replace '/','' -replace '='
}
else {
throw "ConvertTo-Base64UrlString requires string or byte array input, received $($in.GetType())"
}
}