How to Encode and Decode Base64 String in PowerShell

Introduction

Base64 is an encoding schemes for arrays of bytes. It is designed to carry data stored in binary formats that can represent anything. Base64 is widely used with network protocols to send complex data across a network, e.g., email attachments.

In this blog post, we will walk through how to encode and decode Base64 string in PowerShell.

Solution

To encode string to Base64 and decode it, we can use ToBase64String and FromBase64String method from .NET framework respectively.

All samples below will differ only about the encoding and how it use the arguments.

Using PowerShell Convert type

The following example will encode Hello world string to Base64, then decode it to array of bytes that represents Hello world string:

To encode, you can use below command:


[Convert]::ToBase64String([char[]]'Hello world')

To decode, you can use below command:


$bytes = [Convert]::FromBase64String('SGVsbG8gd29ybGQ=')
-join ($bytes -as [char[]])

Using UTF8 from .NET Framework

This solution will use UTF8 property of System.Text.Encoding class from .NET Framework.

To encode, you can use below command:


$script = 'Hello world'
$bytes = [System.Text.Encoding]::UTF8.GetBytes($script)
[Convert]::ToBase64String($bytes)

To decode, you can use below command:


$bytes = [Convert]::FromBase64String('SGVsbG8gd29ybGQ=');
[System.Text.Encoding]::UTF8.GetString($bytes);

Using Unicode from .NET Framework

Similar to previous UTF-8 method, but this time we use Unicode property of System.Text.Encoding class from .NET Framework.

To encode, you can use below command:


$script = 'Hello world'
$bytes = [System.Text.Encoding]::Unicode.GetBytes($script)
[Convert]::ToBase64String($bytes)

To decode, you can use below command:


$bytes = [Convert]::FromBase64String('SABlAGwAbABvACAAdwBvAHIAbABkAA==');
[System.Text.Encoding]::Unicode.GetString($bytes);

Conclusion

In conclusion, to encode a string to Base64 then decode it, we can use ToBase64String and FromBase64String method from PowerShell Convert type and .NET framework. We can choose whether we want to use UTF-8 encoding or Unicode property.