Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Base64 Padding in PowerShell
# define and encode test data
$TestString = 'This is a test. A short test for encoding and padding.'
$Encoded = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($TestString))
# insert random '='
$Length = $Encoded.Length
$RandomChar = 1..($Length - 3) | Get-Random
$Encoded = $Encoded.Insert($RandomChar,'=')
# strip out '='
$Stripped = $Encoded.Replace('=','')
# append appropriate padding
$ModulusValue = ($Stripped.length % 4)
Switch ($ModulusValue) {
'0' {$Padded = $Stripped}
'1' {$Padded = $Stripped.Substring(0,$Stripped.Length - 1)}
'2' {$Padded = $Stripped + ('=' * (4 - $ModulusValue))}
'3' {$Padded = $Stripped + ('=' * (4 - $ModulusValue))}
}
# base64 decode and output
$Decoded = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($Padded))
Write-Output $Decoded
@harre096

This comment has been minimized.

Copy link

commented May 10, 2018

This is magic! Thanks for putting this out here to help folks like me. :)
Can you explain why inserting and stripping out that "=" is needed?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.