Welcome!

Microsoft Cloud Authors: Andreas Grabner, Stackify Blog, Liz McMillan, David H Deans, Automic 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

The numBlocks variable represents the number of three-byte blocks in the input array, and also the number of four-character blocks in the output string. The padBytes variable holds the number of bytes that I will have to pad into the output string to bring the size of the string up to an even multiple of 4. If the size of input array is an even multiple of 3, then the number of blocks is just the size of the input divided by 3 and there is no padding. For example, if the input has size 27 bytes then my encoder will process 27 / 3 = 9 three-byte blocks and produce a string with 9 * 4 = 36 characters. If the input is not an even multiple of 3 then there is one extra block and either one or two padding bytes required. I do a rudimentary validation check:

if (padBytes < 0 || padBytes > 3)
     throw new Exception("Fatal logic error in padding code");

Because this article is primarily a tutorial, I have omitted most of the error-checking code for clarity. In a production system you will need to add a lot of additional error checks. Next, I set up three arrays where most of the encoding work is done:

byte[] newValue = new byte[numBlocks * 3];
for (int i = 0; i < newValue.Length; ++i) // not really necesary
     newValue[i] = 0;
for (int i = 0; i < value.Length; ++i)
     newValue[i] = value[i];

byte[] resultBytes = new byte[numBlocks * 4];
char[] resultChars = new char[numBlocks * 4];

I declare a byte array newValue which will be a copy of the input byte array, but expanded in size up to an even multiple of three bytes if necessary. I do this so I can process three bytes of input at a time. I explicitly zero-out array newValue but this is not necessary because when arrays are declared but not initialized they are filled with the default value for the array contents (which is 0 in this case). Next I copy the original input bytes into the working array newValue. Then I declare a byte array named resultBytes with size four times the number of input blocks. As explained earlier, each three bytes of input produces four characters of output. The resultBytes array will hold the output characters in byte form pending their conversion to characters. The resultChars array will hold the Base64 encoded string result except that it may need padding with one or two "=" characters. The main processing loop iterates through each block of input:

for (int i = 0; i < numBlocks; i++)
{
resultBytes[i * 4 + 0] =
    (byte)((newValue[i * 3 + 0] & 0xFC) >> 2);

resultBytes[i * 4 + 1] =
    (byte)((newValue[i * 3 + 0] & 0x03) << 4 |
       (newValue[i * 3 + 1] & 0xF0) >> 4);

resultBytes[i * 4 + 2] =
    (byte)((newValue[i * 3 + 1] & 0x0F) << 2 |
       (newValue[i * 3 + 2] & 0xC0) >> 6);

resultBytes[i * 4 + 3] =
    (byte)((newValue[i * 3 + 2] & 0x3F));
}

Here is where most of the work is performed. There aren't many lines of code here but they're a bit tricky. The process is best explained with a diagram as shown in Figure 3. To obtain the first character of output, I need to extract the leftmost six bits of the first byte of the input. To do this I can mask by logical ANDing (in C#, with the "&" operator) with value 0xFC, which is 1111 1100 in binary. Now if I perform a logical right shift two bits (using " >> 2"), I will have the leftmost six bits. The other logical operations are similar and if you trace through the masking and bit shifting code with a paper and pencil you'll see how each bye of output is determined. Once I have the output in byte form, I can compute the equivalent character form using my base64Chars lookup table:

for (int i = 0; i < numBlocks * 4; ++i)
     resultChars[i] = base64Chars[resultBytes[i]];

Now all that's left to do is to pad the trailing output characters with "=" where necessary:

if (padBytes == 0)
     ;
else if (padBytes == 1)
     resultChars[numBlocks * 4 - 1] = '=';
else if (padBytes == 2)
{
     resultChars[numBlocks * 4 - 1] = '=';
     resultChars[numBlocks * 4 - 2] = '=';
}

I use the padBytes value I computed earlier and add either two, one, or zero "=" characters at the end of the result char array. The null statement when padBytes has value 0 is a bit ugly and you can leave it out if you wish. I finish the encoding routine by converting the result char array to a string using the overloaded String object constructor, which accepts a character array, and then I return the result string:

string s = new string(resultChars);
return s;

With the custom encoder in place, you can write code that mirrors encoding using the .NET Framework methods. For example:

byte[] input = new byte[] { 0x5F, 0xC9, 0xBF, 0x17 };
string output = MyConverter.ToBase64String(input);
Console.WriteLine(output);

The Custom Base64 Decoder
In most situations a custom Base64 encoder is useless without its corresponding decoder. Listing 2 presents one way to write a Base64 decoder. Because the concepts involved in decoding are essentially the same as those for encoding, I won't go over the decoding implementation in detail.

The private ValueOf() method accepts one of the Base64 characters and returns the numeric value that corresponds to the lookup table in the ToBase64String() method. For example, if the input character is "A," the helper method will return "A" - 65 = 65 - 65 = 0. If you write a custom Base64 encoder with a different character set, then you'll have to modify the logic in ValueOf() accordingly.

Conclusion
The most common use of a Base64 encoding is to send binary data over e-mail in MIME format. The specifications for this particular type of Base64 encoding are contained in RFC 1421 and RFC 2045. Because Base64 encoding is so often associated with MIME, it is easy to incorrectly assume that this is the only kind of Base64 encoding. If you encounter Base64 encoding in a system or specification, make sure you clearly determine what particular flavor of Base64 encoding is being used. For example, MIME Base64 encoding specifies that the encoded output stream must be represented in lines of no more than 76 characters each. However, a generic Base64 encoding scheme may not have this restriction.

The .NET Framework Convert.ToBase64String() and Convert.From-Base64String() methods will meet the majority of your Base64 needs. However, knowing how to implement a custom scheme may be useful in several situations. One possible scenario is that you inherit a legacy system with a custom encoding scheme and you need to decode data from that system. Another possible use of a custom Base64 encoding scheme is to provide rudimentary obfuscation of data. If you use a custom scheme to encode data being transmitted over an open communications channel, you can scramble your data. Of course this is by no means data encryption or a security mechanism - it's just a way to deter casual inspection of your data.

To summarize, Base64 encoding is a way to represent arbitrary binary data as a string composed of characters from a 64-character set. Base64 encoding is useful when you want to transmit binary data over a communication channel that is inherently text-based, such as SMTP or HTTP. Base64 encoding is more efficient in terms of encoding size than basic hexadecimal encoding. The .NET Framework has simple and effective Base64 methods that will suit most of your needs. However if you need to implement a custom Base64 scheme, you can use the custom implementation code presented in this article as a basis to get started.

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
The current age of digital transformation means that IT organizations must adapt their toolset to cover all digital experiences, beyond just the end users’. Today’s businesses can no longer focus solely on the digital interactions they manage with employees or customers; they must now contend with non-traditional factors. Whether it's the power of brand to make or break a company, the need to monitor across all locations 24/7, or the ability to proactively resolve issues, companies must adapt to...
SYS-CON Events announced today that Datanami has been named “Media Sponsor” of 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. Datanami is a communication channel dedicated to providing insight, analysis and up-to-the-minute information about emerging trends and solutions in Big Data. The publication sheds light on all cutting-edge technologies including networking, storage and applications, and the...
SYS-CON Events announced today that EnterpriseTech has been named “Media Sponsor” of 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. EnterpriseTech is a professional resource for news and intelligence covering the migration of high-end technologies into the enterprise and business-IT industry, with a special focus on high-tech solutions in new product development, workload management, increased effi...
SYS-CON Events announced today that MobiDev, a client-oriented software development company, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MobiDev is a software company that develops and delivers turn-key mobile apps, websites, web services, and complex software systems for startups and enterprises. Since 2009 it has grown from a small group of passionate engineers and business...
SYS-CON Events announced today that GrapeUp, the leading provider of rapid product development at the speed of business, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Grape Up is a software company, specialized in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market acr...
SYS-CON Events announced today that Ayehu will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on October 31 - November 2, 2017 at the Santa Clara Convention Center in Santa Clara California. Ayehu provides IT Process Automation & Orchestration solutions for IT and Security professionals to identify and resolve critical incidents and enable rapid containment, eradication, and recovery from cyber security breaches. Ayehu provides customers greater control over IT infras...
Artificial intelligence, machine learning, neural networks. We’re in the midst of a wave of excitement around AI such as hasn’t been seen for a few decades. But those previous periods of inflated expectations led to troughs of disappointment. Will this time be different? Most likely. Applications of AI such as predictive analytics are already decreasing costs and improving reliability of industrial machinery. Furthermore, the funding and research going into AI now comes from a wide range of com...
In this presentation, Striim CTO and founder Steve Wilkes will discuss practical strategies for counteracting fraud and cyberattacks by leveraging real-time streaming analytics. In his session at @ThingsExpo, Steve Wilkes, Founder and Chief Technology Officer at Striim, will provide a detailed look into leveraging streaming data management to correlate events in real time, and identify potential breaches across IoT and non-IoT systems throughout the enterprise. Strategies for processing massive ...
SYS-CON Events announced today that Conference Guru has been named “Media Sponsor” of 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. A valuable conference experience generates new contacts, sales leads, potential strategic partners and potential investors; helps gather competitive intelligence and even provides inspiration for new products and services. Conference Guru works with conference organi...
SYS-CON Events announced today that Cloud Academy named "Bronze Sponsor" of 21st International Cloud Expo which will take place October 31 - November 2, 2017 at the Santa Clara Convention Center in Santa Clara, CA. Cloud Academy is the industry’s most innovative, vendor-neutral cloud technology training platform. Cloud Academy provides continuous learning solutions for individuals and enterprise teams for Amazon Web Services, Microsoft Azure, Google Cloud Platform, and the most popular cloud com...
SYS-CON Events announced today that CA Technologies has been named "Platinum Sponsor" of SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CA Technologies helps customers succeed in a future where every business - from apparel to energy - is being rewritten by software. From planning to development to management to security, CA creates software that fuels transformation for companies in the applic...
SYS-CON Events announced today that TMC has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo and Big Data at Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Global buyers rely on TMC’s content-driven marketplaces to make purchase decisions and navigate markets. Learn how we can help you reach your marketing goals.
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
"MobiDev is a Ukraine-based software development company. We do mobile development, and we're specialists in that. But we do full stack software development for entrepreneurs, for emerging companies, and for enterprise ventures," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
SYS-CON Events announced today that Telecom Reseller has been named “Media Sponsor” of 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. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.
We build IoT infrastructure products - when you have to integrate different devices, different systems and cloud you have to build an application to do that but we eliminate the need to build an application. Our products can integrate any device, any system, any cloud regardless of protocol," explained Peter Jung, Chief Product Officer at Pulzze Systems, in this SYS-CON.tv interview at @ThingsExpo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA
Multiple data types are pouring into IoT deployments. Data is coming in small packages as well as enormous files and data streams of many sizes. Widespread use of mobile devices adds to the total. In this power panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists looked at the tools and environments that are being put to use in IoT deployments, as well as the team skills a modern enterprise IT shop needs to keep things running, get a handle on all this data, and deliver...
The current age of digital transformation means that IT organizations must adapt their toolset to cover all digital experiences, beyond just the end users’. Today’s businesses can no longer focus solely on the digital interactions they manage with employees or customers; they must now contend with non-traditional factors. Whether it's the power of brand to make or break a company, the need to monitor across all locations 24/7, or the ability to proactively resolve issues, companies must adapt to...
SYS-CON Events announced today that Enzu will exhibit at SYS-CON's 21st Int\ernational Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Enzu’s mission is to be the leading provider of enterprise cloud solutions worldwide. Enzu enables online businesses to use its IT infrastructure to their competitive advantage. By offering a suite of proven hosting and management services, Enzu wants companies to focus on the core of their ...