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

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
SYS-CON Events announced today that Telecom Reseller has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. 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.
WebRTC is great technology to build your own communication tools. It will be even more exciting experience it with advanced devices, such as a 360 Camera, 360 microphone, and a depth sensor camera. In his session at @ThingsExpo, Masashi Ganeko, a manager at INFOCOM Corporation, introduced two experimental projects from his team and what they learned from them. "Shotoku Tamago" uses the robot audition software HARK to track speakers in 360 video of a remote party. "Virtual Teleport" uses a multip...
Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
"Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
"There's plenty of bandwidth out there but it's never in the right place. So what Cedexis does is uses data to work out the best pathways to get data from the origin to the person who wants to get it," explained Simon Jones, Evangelist and Head of Marketing at Cedexis, 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 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.
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, 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.
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
It is of utmost importance for the future success of WebRTC to ensure that interoperability is operational between web browsers and any WebRTC-compliant client. To be guaranteed as operational and effective, interoperability must be tested extensively by establishing WebRTC data and media connections between different web browsers running on different devices and operating systems. In his session at WebRTC Summit at @ThingsExpo, Dr. Alex Gouaillard, CEO and Founder of CoSMo Software, presented ...
In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
Leading companies, from the Global Fortune 500 to the smallest companies, are adopting hybrid cloud as the path to business advantage. Hybrid cloud depends on cloud services and on-premises infrastructure working in unison. Successful implementations require new levels of data mobility, enabled by an automated and seamless flow across on-premises and cloud resources. In his general session at 21st Cloud Expo, Greg Tevis, an IBM Storage Software Technical Strategist and Customer Solution Architec...
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...
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 ...
An increasing number of companies are creating products that combine data with analytical capabilities. Running interactive queries on Big Data requires complex architectures to store and query data effectively, typically involving data streams, an choosing efficient file format/database and multiple independent systems that are tied together through custom-engineered pipelines. In his session at @BigDataExpo at @ThingsExpo, Tomer Levi, a senior software engineer at Intel’s Advanced Analytics gr...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things’). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing? IoT is not about the devices, it’s about the data consumed and generated. The devices are tools, mechanisms, conduits. In his session at Internet of Things at Cloud Expo | DXWor...
Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution. In his session at @ThingsExpo, Akvelon expert and IoT industry leader Sergey Grebnov provided an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.
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...
SYS-CON Events announced today that Google Cloud has been named “Keynote 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. Companies come to Google Cloud to transform their businesses. Google Cloud’s comprehensive portfolio – from infrastructure to apps to devices – helps enterprises innovate faster, scale smarter, stay secure, and do more with data than ever before.