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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |