Base32 encoding

by benwylie at 2012-08-23 07:26:23

I would like to convert bytes to Base32 in PowerShell.

I can see that you can convert to hex (base 16) using:
BitConverter.ToString()

and can convert to Base64 using:
Convert.ToBase64String()

Is there a way of converting to Base32 without resorting to third party modules?
by poshoholic at 2012-08-23 07:55:04
Sort of. I don’t think you’ll find a method on an object that converts your array of bytes into Base32. However in doing some quick searching around, I found C# methods written that do this conversion and since PowerShell is based on .NET, you could just translate those into PowerShell to do the work. That would avoid taking a dependency on a 3rd party module.
by poshoholic at 2012-08-23 07:56:55
Also the conversion should be pretty easy since you can use Add-Type to add a class with a C# method. This allows you to use the C# code to convert a byte array to Base32 as is, and then you can just call that from PowerShell. If you need help with this, let me know.
by benwylie at 2012-08-24 07:04:05
Thanks for your help.

I had hoped not to have to resort to that, but now have it working using C# code as you said.

Thanks for your help.
Ben
by MattG at 2012-08-24 07:35:04
It’s really funny you ask because I’m working on a project that requires base32 encoding. It turns out that in <= NET 2.x there is an internal method that will base32 encode a byte array. There is no such method to decode the stream, unfortunately. If you’re feeling adventurous, try the following code:

[script=powershell]# Get reference to private base32 conversion method (Only availble in <= .NET 2.X)
$ToBase32 = [System.IO.IsolatedStorage.IsolatedStorage].GetMethod('ToBase32StringSuitableForDirName', [Reflection.BindingFlags] 'static, nonpublic')

# Read in your file as a byte array
[Byte] $FileBytes = [IO.File]::ReadAllBytes('C:\test.bin')

# Assign the byte array to the first element of an object array
# This is necessary b/c of some casting weirdness when Invoke is called.
$ObjectArray = New-Object Object(1)
$ObjectArray[0] = [Byte] $FileBytes

# Print base32 encoded stream
$ToBase32.Invoke($null, $ObjectArray)[/script]
Again, make sure you’re running v2 of the .NET framework, which should be the case if you’re running PowerShell v2 and haven’t explicitly changed which version of the .NET framework gets loaded. You can confirm which version of .NET with $PSVersionTable.CLRVersion.ToString()

I’m not sure if this will help you but it’s amusing, nonetheless. :smiley: