In previous posts I had written about Base64 decoder and other hashing algorithms using Windows Cryptography functions.  In this post I will write simple C program for BASE64 Encoder.

.

Due to its simplicity BASE64 has become very popular choice for  simple encoding of the passwords or other sensitive data.  But due to its trivial nature of easy decoding made it less useful these days.  Still it is being used as double layer of encoding before storing the encrypted data to disk or storage.

.

Here is the sample C code for BASE64 Encoder.

.

/**
 * characters used for Base64 encoding
 */  
const char *BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

/**
 * encode three bytes using base64 (RFC 3548)
 *
 * @param triple three bytes that should be encoded
 * @param result buffer of four characters where the result is stored
 */  
void _base64_encode_triple(char *triple, char *result)
 {
 int tripleValue, i;

 tripleValue = triple[0];
 tripleValue *= 256;
 tripleValue += triple[1];
 tripleValue *= 256;
 tripleValue += triple[2];

 for (i=0; i<4; i++)
 {
 result[3-i] = BASE64_CHARS[tripleValue%64];
 tripleValue /= 64;
 }
} 

/**
 * Perform BASE64 Encoding of the input text
 *
 */  
BOOL GenerateBase64ForText(char *strSource, size_t sourcelen)
{
 char strTarget[2000]="";
 char *ptrSource = strSource;
 char *ptrTarget = strTarget;

 /* encode all full triples */
 while (sourcelen >= 3)
 {
 _base64_encode_triple(ptrSource, ptrTarget);
 sourcelen -= 3;
 ptrSource += 3;
 ptrTarget += 4;
 }

 /* encode the last one or two characters */
 if (sourcelen > 0)
 {
 unsigned char temp[3];
 memset(temp, 0, sizeof(temp));
 memcpy(temp, ptrSource, sourcelen);

 _base64_encode_triple((char*)temp, ptrTarget);
 *(ptrTarget+3) = '=';

 if( sourcelen == 1 )
 *(ptrTarget+2) = '=';

 ptrTarget += 4;
 }

 /* terminate the string */
 *ptrTarget = 0;

 printf("BASE64 text of input is %s", ptrTarget);

 return TRUE;
} 

Org Source : This is simplified version of http://freecode-freecode.blogspot.com/2008/02/base64c.html

.
In the above program each group of 3 characters from input string are processed and converted to 4 characters. Remaining one or two characters are treated separately by adding special padding character ‘=’.

.

Often base64 encoded strings can be recognized by trailing ‘=’ characters. But the padding character ‘=’ will not be present in the encoded string if the input string is exactly multiple of 3.

Here’s the simple math formula for the final length of BASE64 encoded string
.

Encoded Length =  (Input Length/3)  * 4 +  (Input Length % 3 ) != 0 ?  4  :  0 ;

.

In the coming posts I will throw more light on OpenSSL based crypto functions.  Till they stay tuned to our Twitter for interesting posts !

See Also

CryptoCode: Index of All Crypto Articles