Click here to Skip to main content
Click here to Skip to main content

Base64 Encoding and Decoding

, 6 Jan 2008
Rate this:
Please Sign up or sign in to vote.
Base64 coding/decoding for native C++ and customized coding for C++/CLI.

Introduction

It is a common thing to pass binary data through text-based protocols. One way to manage this is by using Base64 coding.

Background

Base64 is an encoding which uses characters from 'A'-'Z', 'a'-'z', '0'-'9', and the '+', '/' characters. The '=' character is used for padding data.

Value Encoding  Value Encoding  Value Encoding  Value Encoding
   0 A            17 R            34 i            51 z
   1 B            18 S            35 j            52 0
   2 C            19 T            36 k            53 1
   3 D            20 U            37 l            54 2
   4 E            21 V            38 m            55 3
   5 F            22 W            39 n            56 4
   6 G            23 X            40 o            57 5
   7 H            24 Y            41 p            58 6
   8 I            25 Z            42 q            59 7
   9 J            26 a            43 r            60 8
  10 K            27 b            44 s            61 9
  11 L            28 c            45 t            62 +
  12 M            29 d            46 u            63 /
  13 N            30 e            47 v
  14 O            31 f            48 w         (pad) =
  15 P            32 g            49 x
  16 Q            33 h            50 y

The last two characters may change on different systems. One of the reasons could be that you cannot use pure Base64 to send binary data embedded into a URL because the '+' and '/' characters must be encoded with '%2B' and '%2F'. This increases the size of the code, and there may be additional problems (the % character is used by SQL). So sometimes, '+' and '/' have to be replaced; one of the standard replacements are '*' and '-' characters.

Using the Code

Coding is implemented in the Base64 class. It can be used in native and managed applications. The version is chosen by the conditional compilation based on the /clr project options. Macros in the ManagedExt.h header are used to make a transfer from one environment to another easier.

AS_PUBLIC CLASS Base64
{
public:
    static CONST wchar_t CHAR_63 = '*';
    static CONST wchar_t CHAR_64 = '-';

    static int Encode(BYTE_DATA_IN inData, int dataLength, STRING_OUT outCode);
    static int Decode(STRING_IN inCode, int codeLength, BYTE_DATA_OUT outData);
    
    static int GetDataLength(int codeLength);
    static int GetCodeLength(int dataLength);
};
  • Encode - Converts an array of binary data into a string which contains Base64 code. It also returns the size of the produced code (in bytes).
  • Decode - Decodes a string which contains Base64 code and stores it into an output binary data buffer. If the native C++ version is used, the buffer must be pre-allocated. It also returns the number of decoded bytes stored in the output buffer.
  • GetDataLength - Calculates the maximum size of data (in bytes) based on the Base64 code's length.
  • GetCodeLength - Calculates the size of the Base64 code (in bytes) based on the code length. It also includes padding (if it is required). That means that the Decode method can decode less bytes (one or two) than this method returns for the same code length.
  • CHAR_63 and CHAR_64 - These attributes are used to customize the Base64 code to fit our needs (described at the beginning of the article).

The managed version uses the System::Convert class (FromBase64String and ToBase64String). The .NET framework always produces Base64 code with the '+' and '/' characters. The methods of this class replace them with CHAR_63 and CHAR_64, if they are different (when coding), and reverse the changes before decoding.

The GetDataLength method is handy in the native version of the library because the output buffer should be pre-allocated, and this is an easy way to find out how much memory you need.

History

  • 7 November - Fixed the decode routine (miscalculation of size of decoded data).
  • 7 January - A few bug fixes. Customization of padding char added.
  • 5 January - Original version posted.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Mladen Janković
Software Developer
Serbia Serbia
No Biography provided

Comments and Discussions

 
BugCheck this out: Gives totally different answer Pinmemberdash5556-Feb-12 17:37 
BugRe: Check this out: Gives totally different answer Pinmemberdash5556-Feb-12 17:45 
Foll0wing Simple Program gives different answer than your program. Output of this program (MTIzNDU2Nzg5MA==)is identical to the website I mentioned in previous post.
Anything I am missing?
 
using System;
using System.Security.Cryptography;
using System.Text;
 
namespace HashGenerator
{
class Program
{
static void Main (string[] args)
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] keyForHash = encoding.GetBytes("1234567890");
 
Console.WriteLine("\n base64 encoded server response key : " + Convert.ToBase64String(keyForHash));
 
Console.ReadLine();
}
}
}
GeneralRe: Check this out: Gives totally different answer PinmemberMladen Jankovic6-Feb-12 23:34 
GeneralMy vote of 1 Pinmembercipiripper14-Jun-11 0:28 
Questionencoding & decoding error? PinmemberDouble Chiang31-Oct-10 23:34 
AnswerRe: encoding & decoding error? [modified] PinmemberMladen Jankovic4-Nov-10 11:12 
GeneralRe: encoding & decoding error? PinmemberDouble Chiang4-Nov-10 14:22 
GeneralRe: encoding & decoding error? PinmemberMladen Jankovic4-Nov-10 22:24 
GeneralMy vote of 1 PinmemberJim_zhuo28-Sep-10 23:56 
GeneralRe: My vote of 1 PinmemberMladen Jankovic1-Oct-10 3:28 
QuestionHow would you use this to encode a file? Pinmemberkencocomputers4-Mar-10 21:27 
NewsI've converted your code into a pure C version. I think some people may like it. Pinmemberkingsimba051130-Dec-09 18:49 
GeneralBug in Decoding routine PinmemberMember 12514006-Nov-08 13:21 
GeneralRe: Bug in Decoding routine [modified] PinmemberMladen Jankovic7-Nov-08 12:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140721.1 | Last Updated 6 Jan 2008
Article Copyright 2008 by Mladen Janković
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid