Base64 Encoding in Windows PowerShell
Base64 encoding is one of the methods of binary-to-text encoding methods that will represent binary data to a more readable string format.
There are no Windows PowerShell-native commands for Base64 conversion (as of PowerShell [Core] 7.1). So, for now, direct use of the .NET library is needed. This article will show you the possible methods of converting to and from Base64 using Windows PowerShell and the .NET library.
About Base 64
In technical terms, Base64 encoding converts three 8-bit bytes into four 6-bit bytes, consisting of bits numbered 0-63, thus the name Base64. In addition, the decoded data is 3/4 as long as the original string syntax.
While the Base64 encoding method can encode plain text, its real benefit is encoding non-printable characters interpreted by transmitting systems as control characters.
Therefore, you must always explicitly specify what character encoding the Base64 bytes should represent.
Converting To and From Base64
On converting to Base64, you must first obtain a byte representation of the string you’re trying to encode using the character encoding the user of the Base64 string expects.
Also, on converting FROM Base64, you must interpret the resultant array of bytes as a string using the same encoding that we used to create the Base64 representation.
The following examples below will convert to and from UTF-8 encoded string formats using the .NET library:
Converting to Base64:
[Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes('Motorhead'))
Output:
TW90b3JoZWFk
Converting from Base64:
[Text.Encoding]::ASCII.GetString([Convert]::FromBase64String('TW90b3JoZWFk'))
Output:
Motorhead
This article kept defining Base64 encoding as a series of bytes converting to an ASCII string format. However, with Windows PowerShell and the .NET library, we can directly convert to and from other string formats such as Unicode or UTF-8.
To convert to and from UTF-16LE (“Unicode”) or ASCII instead, substitute [Text.Encoding]::Unicode
and [Text.Encoding]::ASCII
for [Text.Encoding]::UTF8
respectively.
Example Syntax:
[Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
[Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.
LinkedIn