Embed Assemblies in PowerShell as Base64 Strings

Image Description

Daily PowerShell #60

Daily PowerShell

December 16, 2021

quote Discuss this Article

In this post, we’ll look at how to embed assemblies in PowerShell as base64 strings.

What is base64?

Base64 is a ASCII representation of binary data. You can convert byte arrays in .NET into base64 strings and back again. Because of this, you can embed binary data into a PowerShell PS1 script as a simple text string.

Generate a Base64 String

To convert a byte array into a base64 string, you can use the Convert class.

[byte[]]$Bytes = @(10, 11, 12)
[Convert]::ToBase64String($Bytes)
# CgsM

Convert a Base64 String to Bytes

You can also use the Convert class to do the opposite.

$Bytes = [Convert]::FromBase64String('CgsM')
# 10
# 11
# 12

Embed an Assembly in a PowerShell Script

You can embed a .NET assembly directly in a PowerShell script and load it with the Assembly class.

First, convert the assembly to base64. This example uses NewtonSoft.Json.

$Bytes = [IO.File]::ReadAllBytes("NewtonSoft.Json.dll")
$Base64 = [Convert]::ToBase64String($Bytes)

Next, in your PS1, you can include the base64 string directly in the code. Then, convert it back to bytes and load it with the assembly class.

$Base64 = "base64-string"
$Bytes = [Convert]::FromBase64String($Base64)
[System.Reflection.Assembly]::Load($Bytes)

Note that AMSI providers like PowerShell Protect may block scripts from loading assemblies in this manner.