Quickie: Powershell Base64 and Base64URL encoding and decoding functions
function Base64Encode ( $s)
{
return [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($s))
}
function Base64Decode ( $s)
{
return [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($s))
}
function Base64URLEncode ( $s)
{
$s = $s.Split('=')[0] #Remove trailing '='s
$s = $s.Replace('+','-');
$s = $s.Replace('/','_');
return Base64Encode ($s)
# Thanks https://stackoverflow.com/a/33113820/7834195
}
function Base64URLDecode ($s)
{
$s = $s.Replace('-','+');
$s = $s.Replace('_','/');
switch ($s.Length % 4) #// Pad with trailing '='s
{
0 { break } # No pad chars in this case
2 { $s+='=='; break } # Two pad chars
3 { $s+='='; break; } # One pad char
Default { throw "Illegal base64url string!" }
}
#[string]$stringToEncode=$text
$return = Base64Decode($s)
return $return
# Thanks https://stackoverflow.com/a/33113820/7834195
}
Comments