BASE64 Encoding and Decoding Using C

hello there,

recently i was struggling to understand how base64 works on windows because i read the RFC and implemented a LIBRARY based on the RFC and it  worked like crippled library, so i started to check the size of the base64 Encoded file and the size of the same file before decoding using C# , and what i found that it seems that it does not comply with the RFC outlines when it comes to the size of pad,

Why i wanted to use base64 encoding ? Because i was writing a DLL using VC++ and i want to use this DLL from .NET web services. so i need to send all the files in Base64 encoded and decoded on my part to do whatever i want then encode it once again and send it to Web services to be consumed by the client application

so the best way i found to do this using C is to use CryptStringToBinary Call which is included in Crypt32.lib.

All you have to do is to configure VC linker Additional dependencies and add this lib,  and from your application you issue two calls

1. to get the length of the decoded buffer so you could allocate it

2. the actual call to do the decoding part

check the code below and enjoy 🙂

WCHAR *decodedDocFile = NULL ; // will hold the decoded content
DWORD cbBinary = 0;            // will hold the size of decoded buffer 
PWSTR pwsPlainFileBase64       // this should be initialized and holds the BASE64 Content

// Get the genertated file size
if (CryptStringToBinary((const PWSTR)pwsPlainFileBase64,
    decodedDocFile = (WCHAR*)malloc(cbBinary);

    // Decode the file so it is prepared for encryption
    if(CryptStringToBinary((const PWSTR)pwsPlainFile,
        printf("File Has been Decoded Successfuly");

and for Encoding use CryptBinaryToString which looks like the following 

BOOL WINAPI CryptBinaryToString(
  _In_       const BYTE *pbBinary,
  _In_       DWORD cbBinary,
  _In_       DWORD dwFlags,
  _Out_opt_  LPTSTR pszString,
  _Inout_    DWORD *pcchString

for more information check the following links

Posted in Programming and tagged , , , , , , , , , . Bookmark the permalink. RSS feed for this post. Leave a trackback.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

Swedish Greys - a WordPress theme from Nordic Themepark.