Base64 Encode/Decode Functions for Powershell

I found the base code for this here: http://vstepic.blogspot.com/2013/02/how-to-convert-string-to-base64-and.html. If you want to know more about Base64, check out this
Wikipedia Entry

But I’m not a command-line guy, I’m a developer, and I like to have my code in a file where I can edit it, modify it, re-use it, and run it.

Function Base64Encode($textIn) 
{
    $b  = [System.Text.Encoding]::UTF8.GetBytes("Hello World")
    $encoded = [System.Convert]::ToBase64String($b)
    return $encoded    
}

Function Base64Decode($textBase64In) 
{
    $b  = [System.Convert]::FromBase64String($textBase64In)
    $decoded = [System.Text.Encoding]::UTF8.GetString($b)
    return $decoded
}

#Test Logic 
$base64Encoded = Base64Encode("Hello World") 
Write-Host "`$base64Encoded=$base64Encoded"

$base64Decoded = Base64Decode($base64Encoded) 
Write-Host "`$base64Decoded=$base64Decoded"

Here is the results of running the above code:
What is your password?: Hello World
$base64Encoded=SGVsbG8gV29ybGQ=
$base64Decoded=Hello World

Now, how can we use this? Let’s take the original code, comment out everything below the “#Test Logic” comment, and save it as “Base64Functions.ps1”.

I wanted to obfuscate a simple password in a config file. Encoding is definitely NOT encryption. But if someone is standing over your shoulder, or even opens the Config File – it will not be obvious that the password is Base64 and they certainly couldn’t convert it in their head or even memorize it.

I found samples for how to update a standard XML Config File at this link: http://blogs.msdn.com/b/sonam_rastogi_blogs/archive/2014/08/18/update-configuration-files-using-powershell.aspx

XML Config File Before:

 

XML Config File After:

. \Base64Functions.ps1  #reference the function created earlier 
cls

#prompt the user to interactively enter his/her password 
$password = Read-Host 'What is your password?'   

#encode it
$base64EncodedPassword = Base64Encode($password)
Write-Host "`$base64EncodedPassword=$base64EncodedPassword"

#store it in our config file in the proper place 
$configFilename = "c:\Users\neal.walters\Documents\GmailConfig.xml"
$xmlConfig = [xml](get-content $configFilename)

$obj = $xmlConfig.configuration.appSettings.add| where {$_.Key -eq 'GmailPassword'}
$obj.Value = $base64EncodedPassword

#we change the xml in memory, so now write it back to the disk file. 
$xmlConfig.Save($configFilename)


Here is the results of running the above code (I typed in “Hello World” in response to the prompt.)
What is your password?: Hello World
$base64Encoded=SGVsbG8gV29ybGQ=
$base64Decoded=Hello World

XML Config File After:


In a future blog, I can show you how I use this to send GMail (Google emails) from Powershell.

Uncategorized  

Leave a Reply