« Maintaining Data Quality in | Main | Unveils Chatter 2 »

Base-64 Encoding in Apex

The other day someone came to me and asked me how to Base64 encode some parameters in an Apex class. Base64 is often used when you need to encode binary data into characters. Base64 is a good way of taking binary data and turning it into text so that it can easily be transmitted in things like HTML form data and email. makes it pretty easy to perform Base-64 encoding in Apex via their EncodingUtil class. Below is an Apex code snippet with a very simple example of the base-64 encode/decode.

    string before = 'Testing base 64 encode';
    // create a blob from our parameter value before we send it as part of the url
    Blob beforeblob = Blob.valueOf(before);
    // base64 encode the blob that contains our url param value
    string paramvalue = EncodingUtil.base64Encode(beforeblob);
    // print out the encoded value to the debug log so we can see it before/after base64 encode
    System.debug(before + ' is now encoded as: ' + paramvalue);
    // take the base64 encoded parameter and create base64 decoded Blob from it
    Blob afterblob = EncodingUtil.base64Decode(paramvalue);
    // Convert the blob back to a string and print it in the debug log
    System.debug(paramvalue + 'is now decoded as: ' + afterblob.toString());

You can refer to EncodingUtil documentation here for more information. In addition, you can take a look at the documentation for the primiatve data type 'blob' here.


PrintView Printer Friendly Version

EmailEmail Article to Friend

Reader Comments (1)

Thanks for this very useful example.

January 16, 2012 | Unregistered CommenterSteve Wallace

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
All HTML will be escaped. Hyperlinks will be created for URLs automatically.