Encode/Decode Base64Url

As is often the case, when working on a project I end up needing some sub-task done and search the web to see if someone have done it before. In this particular instance I couldn’t find any ready-made solutions for PowerShell, but I did find that someone had written a couple of functions in c# that did exactly what I needed. Luckily, translating from c# to PowerShell isn’t that hard, so I thought I’d share the functions I wrote (translated) with you.

NOTE! I take no credit for these functions, other than the fact I translated them from c#. The full credit goes to Jonathan Taylor.

These functions lets you decode and encode to and from Base64 Url.


function Invoke-Base64UrlDecode {
<#
.SYNOPSIS
.DESCRIPTION
.NOTES
http://blog.securevideo.com/2013/06/04/implementing-json-web-tokens-in-net-with-a-base-64-url-encoded-key/
Author: Øyvind Kallstad
Date: 23.03.2015
Version: 1.0
#>
[CmdletBinding()]
param (
[Parameter(Position = 0, Mandatory)]
[string] $Argument
)
$Argument = $Argument.Replace('', '+')
$Argument = $Argument.Replace('_', '/')
switch($Argument.Length % 4) {
0 {break}
2 {$Argument += '=='; break}
3 {$Argument += '='; break}
DEFAULT {Write-Warning 'Illegal base64 string!'}
}
Write-Output $Argument
}


function Invoke-Base64UrlEncode {
<#
.SYNOPSIS
.DESCRIPTION
.NOTES
http://blog.securevideo.com/2013/06/04/implementing-json-web-tokens-in-net-with-a-base-64-url-encoded-key/
Author: Øyvind Kallstad
Date: 23.03.2015
Version: 1.0
#>
[CmdletBinding()]
param (
[Parameter(Position = 0, Mandatory)]
[byte[]] $Argument
)
$output = [System.Convert]::ToBase64String($Argument)
$output = $output.Split('=')[0]
$output = $output.Replace('+', '')
$output = $output.Replace('/', '_')
Write-Output $output
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s