Welcome!

Microsoft Cloud Authors: Janakiram MSV, Yeshim Deniz, David H Deans, Andreas Grabner, Stackify Blog

Related Topics: Microsoft Cloud

Microsoft Cloud: Article

Cover Story: Understanding Base64 Encoding

What it is, when to use it, and how to write custom Base64 encoding

If you work in a .NET environment you have probably come across Base64 encoded data. For example, Base64 encoding is used in ASP.NET for a Web application's ViewState value, as shown in Figure 1. Base64 encoding is also used to transmit binary data over e-mail. However, if you are like most of my colleagues (and me until recently) you do not have a thorough understanding of precisely what Base64 encoding is and when Base64 encoding should be used. In the this article I will explain exactly what Base64 encoding is, show you how to use the two primary .NET Framework methods that support Base64 encoding and decoding, and present a lightweight, custom C# implementation of Base64 encoding and decoding methods. This article assumes you are a .NET developer, tester, or manager and have intermediate level C# coding skill. After reading the article you'll have a solid grasp of Base64 encoding as well as the ability to write your own custom encoding methods. I think you'll find the ability to use Base64 encoded data is a valuable addition to your skill set.

The best way to show you where I'm headed in this article is with a screenshot. If you examine Figure 2 you'll see that I start with the arbitrary string "Hello" and use it to generate some binary data. After displaying the starting binary data in hexadecimal form, I convert the binary data to a Base64 encoded string using a method from the .NET Framework, and also using my custom encoding method. Notice the encoding results are the same. In the next part of the screenshot in Figure 2 I decode the Base64 encoded strings back to their original byte arrays, using both the built-in .NET Framework method and my custom implementation, and display in hexadecimal form. The complete program, which produced the screenshot in Figure 2, is presented in Listing 3.

What Is Base64 Encoding?
Exactly what is Base64 encoding? Base64 encoding is a scheme that encodes arbitrary binary data as a string composed from a set of 64 characters. The exact character set can be any 64 distinct ASCII characters, but by far the most common set is "A" through "Z," "a" through "z," "0" through "9," "+," and "/." For example, using this character set the 40-bit data:

01001000 01100101 01101100 01101100 01101111

can be Base64 encoded as the string:

SGVsbG8=

The trailing "=" character is a padding character as I will explain shortly. After seeing Base64 encoding for the first time, most engineers have an immediate question: Why would anyone want to use Base64 encoding? Base64 encoding is useful when you want to transmit binary data over a communication channel that is designed to transmit character data. For example, consider e-mail. The e-mail protocol SMTP was originally designed to send and receive only simple text data. However, suppose you want to transmit binary data such as a JPEG image. If you can encode the image as a Base64 string, then you can send the image just like any other message. Another common example is sending an ASP.NET Web application's ViewState value (which is a binary value representing the overall state of the application) over HTTP (which is an inherently text-based transport protocol). But why go to the trouble of Base64 encoding when "ordinary" encoding already exists? By ordinary encoding I mean regular hexadecimal encoding. For example, the 40-bit binary data above can be represented as a hexadecimal string: 48 65 6C 6C 6F (where the spaces are included just for readability). The answer is that Base64 encoding is more efficient than hexadecimal encoding in the sense that Base64 encoding requires fewer characters to represent the same data. Notice that the hexadecimal encoding of the 40-bit data above requires 10 characters while Base64 encoding requires only 8 characters - a 20 percent reduction.

Because Base64 encoding only uses 64 characters, any of the characters can be represented with just 6 bits because 26 = 64. Or, put another way, using 6 bits you can represent data in the range 000000b to 111111b, which is 0d to 63d. This is the key to Base64 encoding efficiency. The best way to explain how Base64 encoding works is with a picture as shown in Figure 3.

Suppose the first three bytes of input to be encoded are 48h, 65h, and 6Ch. In Figure 3 these values are shown in their binary representation: 01001000, 01100101, and 01101100. The first six bits of input, 010010, have value 18d, which in turn maps to character [18] in the Base64 character set, which is "S." The second six bits of input - the last two bits of the first byte of input and the first four bits of the second byte of input - equal 6d, which maps to character "G," and so on. Notice that three bytes of input map neatly to four character of output. Because of this it is convenient to implement Base64 encoding in "blocks" that represent a group of three bytes of input, or four characters of output.

NET Support for Base64 Encoding
The .NET Framework supports Base64 encoding with two methods. The Convert.ToBase64String() method accepts a byte array as an input argument and returns a Base64 encoded string (using the usual 64-character set described in the previous section). The Convert.FromBase64String() accepts a string argument (which is assumed to be a valid Base64 encoded string) and returns the corresponding byte array. Using these two methods is very easy. Notice both methods belong to the Convert class and are static so you do not need to instantiate an object to use the methods. The Convert class is part of the System namespace. Consider this code snippet:

byte[] bytes = new byte[] { 0x5F, 0xC9, 0xBF, 0x17 };
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);

This code would produce "X8m/Fw==" as output. Notice that the input has size 4 bytes. The first three bytes (3 * 8 = 24 bits) of input are used to produce the first four Base64 characters (4 * 6 = 24 bits) of output. The last input byte produces the rest of the output, and the output is padded with "=" characters to bring the output size up to an even multiple of 4. The technique to decode is similar. The statements

string encoded = "X8m/Fw==";
byte[] result = Convert.FromBase64String(encoded);
Console.WriteLine(BitConverter.ToString(result));

produce "5F-C9-BF-17" as output. The Framework Base64 methods are simple and straightforward. However, if you are encoding, transmitting, and decoding large amounts of binary data, it is up to you write auxiliary code, which buffers the process by breaking the input data into manageable-sized chunks.

A Lightweight Custom Base64 Encoder
The .NET Framework's ToBase64-String() and FromBase64String() methods will meet most of your Base64 encoding needs. However what if you are developing a system and need a slightly different encoding scheme? For instance, you may want to use a different character set than the normal{"A"-"Z," "a"-"z," "0"-9," "+," "/"} set. In this section I'll present a lightweight, custom Base64 encoder written in C# that you can use as a starting point for your own custom encoder. If you search the Internet you'll find quite a few Base64 encoding examples. The one I present here is a hybrid of several I found combined with one I wrote recently, and is designed for maximum clarity rather than for efficiency. The custom encoder is presented in Listing 1.

Because I want my customer encoder to mimic the interface of the Framework encoder, I begin by creating an overall structure of:

public class MyConverter
{
    public static string ToBase64String(byte[] value)
   {
      // implementation goes here
}
} // class MyConverter

Of course there are many other design alternatives, but making the custom encoder signature the same as the Framework's encoder signature makes sense. I begin my encoder implementation by declaring an array of the 64 characters I want to use for my encoding:

char[] base64Chars = new char[]
{ 'A','B','C','D','E','F','G','H','I','J','K','L','M',
'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
'a','b','c','d','e','f','g','h','i','j','k','l','m',
'n','o','p','q','r','s','t','u','v','w','x','y','z',
'0','1','2','3','4','5','6','7','8','9','+','/' };

This array acts as a lookup table to map a decimal value in the range 0 - 63 to a Base64 character. For example, 0 maps to "A," 1 maps to "B," and 26 maps to "a." I use the normal character set but you can use different characters, or change the order for a custom encoding scheme. Next I compute two values that will control the encoding algorithm:

int numBlocks;
int padBytes;
if ((value.Length % 3) == 0)
{
     numBlocks = value.Length / 3;
     padBytes = 0;
}
else
{
     numBlocks = 1 + (value.Length / 3);
     padBytes = 3 - (value.Length % 3);
}

More Stories By James McCaffrey

Dr. James McCaffrey works for Volt Information Sciences, Inc., where he manages technical training for software engineers working at Microsoft's Redmond, WA campus. He has worked on several Microsoft products, including Internet Explorer and MSN Search. James can be reached at [email protected] or [email protected]

Comments (3) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
trash_incinerator 02/19/10 01:17:00 PM EST

With all due respect to the author, your explanation for why Base64 encoding exists is wrong. The "string" of hex for your example is not comprised of 10 characters as you have indicated. Hex uses 2 digits to represent 8 bits. Four bits for the first digit and four bits for the second. There are, in fact, only 5 bytes of data there, whereas the Base64 encoded string is using 8 bytes.

Base64 is NOT a means of compressing data. In fact it makes the information being represented larger. The reason why this is sometimes necessary is because of the fact that systems assign special meanings to specific bytes or byte sequences. In XML for example, there are special bytes that are not considered valid characters in XML. In order to send information in an XML stream with characters that are not allowed, you have to replace the illegal bytes with legal ones. Hence, Base64 allows you to take arbitrary bytes and reassign them in a way that can be reversed later.

Kumanan Murugesan 04/16/08 10:07:55 AM EDT

Dr. James,
Wonderful article. I was wondering what this does and why is it required many times like other folks.

SYS-CON Belgium News Desk 03/19/06 10:04:38 AM EST

If you work in a .NET environment you have probably come across Base64 encoded data. For example, Base64 encoding is used in ASP.NET for a Web application's ViewState value, as shown in Figure 1. Base64 encoding is also used to transmit binary data over e-mail. However, if you are like most of my colleagues (and me until recently) you do not have a thorough understanding of precisely what Base64 encoding is and when Base64 encoding should be used. In the this article I will explain exactly what Base64 encoding is, show you how to use the two primary .NET Framework methods that support Base64 encoding and decoding, and present a lightweight, custom C# implementation of Base64 encoding and decoding methods. This article assumes you are a .NET developer, tester, or manager and have intermediate level C# coding skill. After reading the article you'll have a solid grasp of Base64 encoding as well as the ability to write your own custom encoding methods. I think you'll find the ability to use Base64 encoded data is a valuable addition to your skill set.

@ThingsExpo Stories
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, whic...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...
In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
"Digital transformation - what we knew about it in the past has been redefined. Automation is going to play such a huge role in that because the culture, the technology, and the business operations are being shifted now," stated Brian Boeggeman, VP of Alliances & Partnerships at Ayehu, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Synametrics Technologies will exhibit at SYS-CON's 22nd International Cloud Expo®, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Synametrics Technologies is a privately held company based in Plainsboro, New Jersey that has been providing solutions for the developer community since 1997. Based on the success of its initial product offerings such as WinSQL, Xeams, SynaMan and Syncrify, Synametrics continues to create and hone inn...
"Evatronix provides design services to companies that need to integrate the IoT technology in their products but they don't necessarily have the expertise, knowledge and design team to do so," explained Adam Morawiec, VP of Business Development at Evatronix, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
The 22nd International Cloud Expo | 1st DXWorld Expo has announced that its Call for Papers is open. Cloud Expo | DXWorld Expo, to be held June 5-7, 2018, at the Javits Center in New York, NY, brings together Cloud Computing, Digital Transformation, Big Data, Internet of Things, DevOps, Machine Learning and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding busin...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, discussed how they built...
SYS-CON Events announced today that Evatronix will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Evatronix SA offers comprehensive solutions in the design and implementation of electronic systems, in CAD / CAM deployment, and also is a designer and manufacturer of advanced 3D scanners for professional applications.
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
DevOps at Cloud Expo – being held June 5-7, 2018, at the Javits Center in New York, NY – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real results. Among the proven benefits,...
@DevOpsSummit at Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, is co-located with 22nd Cloud Expo | 1st DXWorld Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait...
SYS-CON Events announced today that T-Mobile exhibited at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on qua...