Base64 Encode/Decode a string

Base64 Encode/Decode a string

Rate This
  • Comments 7

Today I came across http://scripts.readify.net/  . This sight is focused on Monad and MSH and is starting a collection of scripts at: http://scripts.readify.net/Scripts.aspx .  You should visit their site and let them know what type of scripts would be useful to you. 

I particularly liked their entry on how to Base64 encode a file.  This is something that I need occassionally and I can never remember how to do it.  I was about to include it as-is into my profile and decided that there was a better way to do this. 

<IMPORTANT POINT>
Whenever you are adding some functions, you should make a conscious decision about whether those functions are best exposed as a "function" or as a "type extension".
</IMPORTANT POINT>

Both of these mechanisms are great and have their purpose but my observation is that people are not using type-extensions as much as they should.  One of the huge benefits of type extensions is discoverability.  Let me show you how to do this function as a type-extension and highlight the benefits of this approach.

When doing a type extension, you first need to decide what TYPE you are going to extend.  In this case, I decided that I would extend SYSTEM.STRING as that was the most general purpose type for this function.  I then encoded the following in a file called My.Types.Mshxml

</Types>
    <Type>
        <Name>System.String</Name>
        <Members>
            <ScriptProperty>
                <Name>ToBase64String</Name>
                <GetScriptBlock>
                 [System.Convert]::ToBase64String([System.Text.Encoding]::UNICODE.GetBytes($this))
  </GetScriptBlock>
            </ScriptProperty>
            <ScriptProperty>
                <Name>FromBase64String</Name>
                <GetScriptBlock>
                 [System.Text.Encoding]::UNICODE.GetString([System.Convert]::FromBase64String($this))
  </GetScriptBlock>
            </ScriptProperty>
        </Members>
    </Type>
</Types>

 

In my profile I load this file via the command:

   Update-TypeData c:\msh\My.Types.mshxml

Once I do that, these properties are available to any STRING and can be discovered via Get-Member:

MSH> $x="Hello World"
MSH> $x |Get-Member


   TypeName: System.String

Name             MemberType            Definition
----             ----------            ----------
Clone            Method                System.Object Clone()
CompareTo        Method                System.Int32 CompareTo(Object value), System.Int32 CompareTo(String strB)
Contains         Method                System.Boolean Contains(String value)
CopyTo           Method                System.Void CopyTo(Int32 sourceIndex, Char[] destination, Int32 destinationIndex, Int32 count)
EndsWith         Method                System.Boolean EndsWith(String value), System.Boolean EndsWith(String value, StringComparison comparisonType), System.Boolean EndsWith(String value, Boolean ignoreCase, CultureInfo culture)
...

Trim             Method                System.String Trim(Params Char[] trimChars), System.String Trim()
TrimEnd          Method                System.String TrimEnd(Params Char[] trimChars)
TrimStart        Method                System.String TrimStart(Params Char[] trimChars)
Chars            ParameterizedProperty System.Char Chars(Int32 index) {get;}
Length           Property              System.Int32 Length {get;}
FromBase64String ScriptProperty        System.Object FromBase64String {get=[System.Text.Encoding]::UNICODE.GetString([System.Convert]::FromBase64String($this));}
ToBase64String   ScriptProperty        System.Object ToBase64String {get=[System.Convert]::ToBase64String([System.Text.Encoding]::UNICODE.GetBytes($this));}


MSH> $x
Hello World
MSH> $x.ToBase64String
SABlAGwAbABvACAAVwBvAHIAbABkAA==
MSH> $x.ToBase64String.FromBase64String
Hello World
MSH>

 

Enjoy!

Jeffrey Snover
Monad Architect

[Edit: Monad has now been renamed to Windows PowerShell. This script or discussion may require slight adjustments before it applies directly to newer builds.]

PSMDTAG:CMDLET: Update-TypeData

PSMDTAG:FAQ: How do I base64 encode/decode a string?

PSMDTAG:PHILOSOPHY: Whenever you are adding some functions, you should make a conscious decision about whether those functions are best exposed as a "function" or as a "type extension".

PSMDTAG:DOTNET: System.Convert, System.Text.Encoding

PSMDTAG:TYPEEXTENSION: System.String

Leave a Comment
  • Please add 5 and 2 and type the answer here:
  • Post
  • great blog
  • Hi,

    I am trying to encode Chinese characters into Base64 and decode them back. But what I decode them back I am only getting ????? (question marks are displayed).

    Does anyone out there had a similar problem.

    I am using javax.mail.internet.*;

    String chineseString = "漢字万维读者网 · 联合早报 · 雅虎中文新闻 · 北美新浪 · BBC中文网 · 自由亚洲电台 · 多维新闻网 · 大纪元新闻网 · 博讯新闻网 · 星岛日报(美) · 星岛日报(加)";

    encodedString = MimeUtility.encodeText(chineseString,"utf-16","B");

    decodedString = MimeUtility.decodeText(encodedString);

    I also tried to write out the decoded string into a html file and opened with browser. Only question marks are displayed instead of the actual characters.

  • TYPO: First line of code should be <Types>

  • PingBack from http://www.aaronlerch.com/blog/2007/05/07/type-extensions/

  • Awesome - but the two (scripts.redify) links don't seem to work anymore? Any chance you could post the new links?

  • yeah, can you repost the links. thanks

  • There's a typo in the XML. The first line should be "<Types>" not "</Types>". Also, the cmdlet apparently wants the file type of the file to be .PS1XML instead of MSHXML. Still, awesome stuff, thanks!

Page 1 of 1 (7 items)