Created
April 15, 2015 17:58
-
-
Save obscuresec/82775093ad892ef5fd00 to your computer and use it in GitHub Desktop.
Base64 Padding in PowerShell
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
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?