Welcome!

Microsoft Cloud Authors: David H Deans, Yeshim Deniz, Janakiram MSV, 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 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...
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...
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, will introduce 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...
SYS-CON Events announced today that Calligo has been named “Bronze 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. Calligo is an innovative cloud service provider offering mid-sized companies the highest levels of data privacy. Calligo offers unparalleled application performance guarantees, commercial flexibility and a personalized support service from its globally located cloud platform...
SYS-CON Events announced today that Elastifile 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. Elastifile Cloud File System (ECFS) is software-defined data infrastructure designed for seamless and efficient management of dynamic workloads across heterogeneous environments. Elastifile provides the architecture needed to optimize your hybrid cloud environment, by facilitating efficient...
SYS-CON Events announced today that Cloudistics, an on-premises cloud computing company, has been named “Bronze 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. Launched in 2016, Cloudistics helps anyone bring the power of the cloud to the data center in an easy-to-use, on- premises cloud platform that automatically provides high performance resources for all types of applications: Docke...
SYS-CON Events announced today that Golden Gate University 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. Since 1901, non-profit Golden Gate University (GGU) has been helping adults achieve their professional goals by providing high quality, practice-based undergraduate and graduate educational programs in law, taxation, business and related professions. Many of its courses are taug...
SYS-CON Events announced today that Golden Gate University 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. Since 1901, non-profit Golden Gate University (GGU) has been helping adults achieve their professional goals by providing high quality, practice-based undergraduate and graduate educational programs in law, taxation, business and related professions. Many of its courses are taug...
SYS-CON Events announced today that Secure Channels, a cybersecurity firm, 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. Secure Channels, Inc. offers several products and solutions to its many clients, helping them protect critical data from being compromised and access to computer networks from the unauthorized. The company develops comprehensive data encryption security strategie...
Recently, WebRTC has a lot of eyes from market. The use cases of WebRTC are expanding - video chat, online education, online health care etc. Not only for human-to-human communication, but also IoT use cases such as machine to human use cases can be seen recently. One of the typical use-case is remote camera monitoring. With WebRTC, people can have interoperability and flexibility for deploying monitoring service. However, the benefit of WebRTC for IoT is not only its convenience and interopera...
SYS-CON Events announced today that SkyScale 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. SkyScale is a world-class provider of cloud-based, ultra-fast multi-GPU hardware platforms for lease to customers desiring the fastest performance available as a service anywhere in the world. SkyScale builds, configures, and manages dedicated systems strategically located in maximum-security...
SYS-CON Events announced today that Datera 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. Datera offers a radically new approach to data management, where innovative software makes data infrastructure invisible, elastic and able to perform at the highest level. It eliminates hardware lock-in and gives IT organizations the choice to source x86 server nodes, with business model option...
SYS-CON Events announced today that DXWorldExpo has been named “Global 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. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
21st International Cloud Expo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, 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 strategy. Me...
SYS-CON Events announced today that Massive Networks 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. Massive Networks mission is simple. To help your business operate seamlessly with fast, reliable, and secure internet and network solutions. Improve your customer's experience with outstanding connections to your cloud.
When shopping for a new data processing platform for IoT solutions, many development teams want to be able to test-drive options before making a choice. Yet when evaluating an IoT solution, it’s simply not feasible to do so at scale with physical devices. Building a sensor simulator is the next best choice; however, generating a realistic simulation at very high TPS with ease of configurability is a formidable challenge. When dealing with multiple application or transport protocols, you would be...
SYS-CON Events announced today that Akvelon 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. Akvelon is a business and technology consulting firm that specializes in applying cutting-edge technology to problems in fields as diverse as mobile technology, sports technology, finance, and healthcare.
SYS-CON Events announced today that Secure Channels, a cybersecurity firm, 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. Secure Channels, Inc. offers several products and solutions to its many clients, helping them protect critical data from being compromised and access to computer networks from the unauthorized. The company develops comprehensive data encryption security strategie...
SYS-CON Events announced today that WineSOFT 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. Based in Seoul and Irvine, WineSOFT is an innovative software house focusing on internet infrastructure solutions. The venture started as a bootstrap start-up in 2010 by focusing on making the internet faster and more powerful. WineSOFT’s knowledge is based on the expertise of TCP/IP, VPN, SS...
WebRTC is the future of browser-to-browser communications, and continues to make inroads into the traditional, difficult, plug-in web communications world. The 6th WebRTC Summit continues our tradition of delivering the latest and greatest presentations within the world of WebRTC. Topics include voice calling, video chat, P2P file sharing, and use cases that have already leveraged the power and convenience of WebRTC.