In previous blog posts I had written about MD5 & SHA256 Hash generation algorithms as well as DES Encryption/Decryption methods using Windows Cryptography Functions.  Today I am going to present a crypto program for Base64 Decoder – very popular encoding algorithm.

.

Base64 is commonly used along side the encryption/decryption algorithms as a double layer of protection and also for making it easier to store the final encrypted data to disk or registry. Even there are applications which only uses BASE64 encoding for storing the secret passwords. Not only this makes it easier in implementation but also prevents hassles of going through any state imposed export laws.

.

Now with the basic facts aside, lets get straight to the C program which implements this Base64 Decoder.

.

//
//  Program to Decode Base64 String
//
int Base64Decoder(char *input, char *output)
{
 char base64string[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
 BYTE dataBuffer[4];
 BYTE outputBuffer[3];
 BYTE finalBuffer[1000];
 int count=0;
 int padCount=0;
 int length;

 length = strlen(input);

 //Validate the data for BASE64
 if( length % 4 )
 {
 printf("%s - Invalid base64 data is supplied %s (%d) ", input, length);
 return 0;
 }

 //count the no of padding
 if (input[length-1] == '=')
 padCount++;

 if (input[length-2] == '=')
 padCount++;

 // Process 4 chars in each loop to produce 3 chars
 for (int i=0; i < length; i += 4)
 {

 // Populate data buffer with position of Base64 characters for
 // next 4 bytes from encoded data
 for (int j=0; j < 4 && (i + j < length); j++) 
 dataBuffer[j] = ( (int)strchr(base64string, input[i+j]) - (int)base64string );


 //Decode data buffer back into bytes
 outputBuffer[0] = (dataBuffer[0] << 2) + ((dataBuffer[1] & 0x30) >> 4);
 outputBuffer[1] = ((dataBuffer[1] & 0x0f) << 4) + ((dataBuffer[2] & 0x3c) >> 2);        
 outputBuffer[2] = ((dataBuffer[2] & 0x03) << 6) + dataBuffer[3];


 // Add all non-padded bytes in output buffer to decoded data
 for (int k = 0; k < 3; k++)
 finalBuffer[count++]=outputBuffer[k];

 }

 count = count-padCount;


 //copy the decoded data into input buffer
 memcpy(output, finalBuffer, count);
 output[count]='\0';

 printf("Base64 decoded string is [%s] (%d) ", output, count);

 return count;
}

.

The above program is more or less self explainatory with most of error handling. Initially it checks if the input string confirms to Base64 standards. Then in each step of the loop, it operates on 4 characters to produce 3 base64 decoded characters. At the end decoded string is copied to the user buffer and returns the total number of characters.

You can use below code snippet to invoke this function from your program,

char strBuffer[1000];

outputLength =Base64Decoder(strEncData, strBuffer);

.

I will be writing more code examples in this CrytoCode series soon. Till then stay tuned to our Twitter post for more interesting stuff !

.

See Also

CryptoCode: Index of All Crypto Articles