How to Encode and Decode Strings with Base64 in PowerShell

When dealing with data that needs to be safely transmitted or stored, encoding the information into a format that is safe for such transmissions is essential. PowerShell provides a straightforward method to encode and decode strings using Base64. Here’s a step-by-step guide on how to use Base64 encoding in PowerShell:

The Encode Function

The Encode function converts a string into a Base64 encoded string. Here’s how it’s defined:

function Encode {
    param([string]$Text)
    $Encoded = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($Text))
    return $Encoded
}

Explanation:

  • Input Parameter: The function accepts a string input $Text.
  • Encoding Process: It converts the input text into a byte array using Unicode encoding and then transforms these bytes into a Base64 string.

The Decode Function

Similarly, the Decode function reverses the process, converting a Base64 encoded string back into readable text:

function Decode {
    param([string]$Encoded)
    $Decoded = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($Encoded))
    return $Decoded
}

Explanation:

  • Input Parameter: This function takes a Base64 encoded string $Encoded.
  • Decoding Process: It converts the Base64 string back into a byte array and then transforms these bytes back into the original string using Unicode decoding.

Using the Functions

To see these functions in action, let’s encode and decode a sample string:

  1. Original String:
$NotEncoded = "This is some text I'd like to encode."
$NotEncoded
  1. Encoding the String:
$EncodedText = Encode -Text $NotEncoded
$EncodedText
  1. Decoding the String:
$Decoded = Decode -Encoded $EncodedText
$Decoded

Output

After running the script, you will observe the following:

  • The original string is displayed.
  • The string is encoded into a Base64 format.
  • The encoded string is then decoded back to its original form.

By using these PowerShell functions, you can easily handle the encoding and decoding of strings in your scripts, ensuring that data can be transmitted safely and securely over environments that might not handle binary data correctly.