Encoding and Decoding PowerShell Strings

Every few months Base64 comes up and I have to go looking for that one post I saw that one time. It’s because that code, on that one site, hasn’t been memorized — not by me, anyway. So, here it is. The below example shows how to encode and decode a string using Base64. Keep in mind that different things, such as HTTP Headers, might require different character sets. In this example, I’m using UTF-8, but it could have been ASCII, or Unicode, or something else.

Clear-Host
$UserName = 'tommymaynard'
$Password = 'password'

"The UserName is '$UserName' and the password is '$Password'."
"Encoding as $($UserName):$($Password)"

$Text = "$($UserName):$($Password)"
$Bytes = [System.Text.Encoding]::UTF8.GetBytes($Text)
$EncodedText =[Convert]::ToBase64String($Bytes)
"Encoded text: $EncodedText"

$DecodedText = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($EncodedText))
"Decoded text: $DecodedText"

When the above code is executed it produces the below results.

The UserName is 'tommymaynard' and the password is 'password'.
Encoding as tommymaynard:password
Encoded text: dG9tbXltYXluYXJkOnBhc3N3b3Jk
Decoded text: tommymaynard:password

And, now that’s that. When I need this next, it’ll be right here on my own blog. Now back to that Python to PowerShell project where I need Base64 encoding. By the way, this is a great online encode/decode tool that you might find helpful: https://www.base64decode.org.

Leave a Reply

Your email address will not be published. Required fields are marked *