Skip to content

Instantly share code, notes, and snippets.

@gitfvb
Created November 1, 2019 10:31
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 gitfvb/375b0c0a891f8ca74e702a4e057ffcd1 to your computer and use it in GitHub Desktop.
Save gitfvb/375b0c0a891f8ca74e702a4e057ffcd1 to your computer and use it in GitHub Desktop.
Base64 String converting in PowerShell because some frameworks trim the "=" at the end
# source of functions: https://medium.com/@nikitafed9292/net-base64-decoding-workaround-82b797162b6e
# Add missing "=" at the end
Function Check-Base64 {
param(
[Parameter(Mandatory=$true)][String]$inputString
)
$input
$encoded = $inputString.Replace('-','+').Replace('_','/')
$d = $encoded.Length % 4
if ( $d -ne 0 ) {
$encoded = $encoded.TrimEnd('=')
if ( $d % 2 -gt 0 ) {
$encoded += '='
} else {
$encoded += '=='
}
}
return $encoded
}
# Remove "=" at the end
Function Trim-Base64 {
param(
[Parameter(Mandatory=$true)][String]$inputString
)
return $inputString.TrimEnd('=')
}
# Example
$payload = [ordered]@{
"sub" = "1234567890"
"name" = "John Doe"
"iat" = 1516239022
}
$payloadBase64 = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(($payload | ConvertTo-Json -Compress)),[Base64FormattingOptions]::None)
$payloadBase64Trimmed = Trim-Base64 -inputString $payloadBase64
$payloadBase64Checked = Check-Base64 -input $payloadBase64Trimmed
"input: $( $payloadBase64 )"
"trimmed: $( Trim-Base64 -inputString $payloadBase64 )"
"checked: $( Check-Base64 -input $payloadBase64Trimmed )"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment