Skip to content

Instantly share code, notes, and snippets.

@obscuresec
Created April 15, 2015 17:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save obscuresec/82775093ad892ef5fd00 to your computer and use it in GitHub Desktop.
Save obscuresec/82775093ad892ef5fd00 to your computer and use it in GitHub Desktop.
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
Copy link

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