Last active
February 5, 2020 20:03
-
-
Save mgeeky/a2f29c0f158033155682c204368a4eeb to your computer and use it in GitHub Desktop.
Base64 Decode 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
function Decode-Base64Ascii ($data) { | |
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" | |
$ss = "[^" + $chars + "=]" | |
$data = $data -replace $ss, "" | |
$pad = "" | |
$r = "" | |
if (($data[$data.Length - 1]) -eq '=') { | |
if (($data[$data.Length - 2]) -eq '=') { | |
$pad = "AA" | |
} else { | |
$pad = "A" | |
} | |
} | |
$data = $data.Substring(0, $data.Length - $pad.Length) + $pad | |
for($c = 0; $c -lt $data.Length ; $c += 4) { | |
$n = ($chars.IndexOf($data[$c]) -shl 18) ` | |
+ ($chars.IndexOf($data[$c + 1]) -shl 12) ` | |
+ ($chars.IndexOf($data[$c + 2]) -shl 6) ` | |
+ ($chars.IndexOf($data[$c + 3])) | |
$r += "" + [char](($n -shr 16) -band 0xff) | |
$r += "" + [char](($n -shr 8) -band 0xff) | |
$r += "" + [char]($n -band 0xff) | |
} | |
return $r.Substring(0, $r.Length - $pad.Length) | |
} | |
function Decode-Base64 ($data) { | |
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" | |
$ss = "[^" + $chars + "=]" | |
$data = $data -replace $ss, "" | |
$pad = "" | |
[byte[]]$r = @() | |
if (($data[$data.Length - 1]) -eq '=') { | |
if (($data[$data.Length - 2]) -eq '=') { | |
$pad = "AA" | |
} else { | |
$pad = "A" | |
} | |
} | |
$data = $data.Substring(0, $data.Length - $pad.Length) + $pad | |
for($c = 0; $c -lt $data.Length ; $c += 4) { | |
$n = ($chars.IndexOf($data[$c]) -shl 18) ` | |
+ ($chars.IndexOf($data[$c + 1]) -shl 12) ` | |
+ ($chars.IndexOf($data[$c + 2]) -shl 6) ` | |
+ ($chars.IndexOf($data[$c + 3])) | |
$r += [byte](($n -shr 16) -band 0xff) | |
$r += [byte](($n -shr 8) -band 0xff) | |
$r += [byte]($n -band 0xff) | |
} | |
$dif = $r.Length - $pad.Length | |
return $r[0..$dif] | |
} | |
# Set-Content -Path $Env:Temp\foo.bin -Encoding Byte -Value $someEncodedValue |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment