Base64 encoding and decoding with PowerShell
July 19th, 2009
A few days ago, I needed to perfom some simple obfuscation on a string. Since I had used Base-64 encoding for this purpose in the past, I needed to find a quick way to perform Base-64 encoding and decoding with PowerShell. Surprisingly, I couldn’t find a blog post or tutorial detailing a simple, straight-forward way of performing this task, though I knew it was easy to do. Since it took me a while to sort it out, I figured that it would be a good idea to throw together a couple of functions for public consumption.
First we have the encode function.
function ConvertTo-Base64($string) {
$bytes = [System.Text.Encoding]::UTF8.GetBytes($string);
$encoded = [System.Convert]::ToBase64String($bytes);
return $encoded;
}
Then, we have the decode function.
function ConvertFrom-Base64($string) {
$bytes = [System.Convert]::FromBase64String($string);
$decoded = [System.Text.Encoding]::UTF8.GetString($bytes);
return $decoded;
}
Simple, straight forward. Also notice that I used UTF8 for the initial encoding. Feel free to substitute for UNICODE or whatever, as per your requirements. For a list of what’s available
to System.Text.Encoding, try running the following.
PS > [System.Text.Encoding] | gm -static -membertype property
TypeName: System.Text.Encoding
Name MemberType Definition
---- ---------- ----------
ASCII Property static System.Text.Encoding ASCII {get;}
BigEndianUnicode Property static System.Text.Encoding BigEndianUnicode {get;}
Default Property static System.Text.Encoding Default {get;}
Unicode Property static System.Text.Encoding Unicode {get;}
UTF32 Property static System.Text.Encoding UTF32 {get;}
UTF7 Property static System.Text.Encoding UTF7 {get;}
UTF8 Property static System.Text.Encoding UTF8 {get;}
Let’s test it out.
PS > $encoded = ConvertTo-Base64 'www.google.com'
PS > $encoded
d3d3Lmdvb2dsZS5jb20=
PS > $decoded = ConvertFrom-Base64 $encoded
PS > $decoded
www.google.com
PS >
There you have it.
Categories: PowerShell




