Neither one nor Many

 
March 2 2011

Probably lots of them on the internet, but I made one myself (don't ask me why) Just searched for some encode and decode functions w/google codesearch, then added a simple main().

Usage: base64conv.exe [OPTION] [SOURCE] [DEST]
 where [OPTION] is either --to-base64 or --from-base64,
  [SOURCE] is the file to convert
  [DEST] is the target/output file (will be overwritten)

Examples: base64conv.exe --to-base64 somefile.exe somefile.txt
          base64conv.exe --from-base64 somefile.txt somefile.exe
(something like ./base64conv on linux)

Here you have it:

/*
   base64.cpp and base64.h

   Copyright (C) 2004-2008 Rene Nyffenegger

   This source code is provided 'as-is', without any express or implied
   warranty. In no event will the author be held liable for any damages
   arising from the use of this software.

   Permission is granted to anyone to use this software for any purpose,
   including commercial applications, and to alter it and redistribute it
   freely, subject to the following restrictions:

   1. The origin of this source code must not be misrepresented; you must not
      claim that you wrote the original source code. If you use this source code
      in a product, an acknowledgment in the product documentation would be
      appreciated but is not required.

   2. Altered source versions must be plainly marked as such, and must not be
      misrepresented as being the original source code.

   3. This notice may not be removed or altered from any source distribution.

   Rene Nyffenegger rene.nyffenegger@adp-gmbh.ch

*/

#include <iostream>

static const char base64_chars[] =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "abcdefghijklmnopqrstuvwxyz"
    "0123456789+/";

static char *
    base64_encode(const unsigned char *input, int length)
{
    /* http://www.adp-gmbh.ch/cpp/common/base64.html */
    int i=0, j=0, s=0;
    unsigned char char_array_3[3], char_array_4[4];

    int b64len = (length+2 - ((length+2)%3))*4/3;
    char *b64str = new char[b64len + 1];

    while (length--) {
        char_array_3[i++] = *(input++);
        if (i == 3) {
            char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
            char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
            char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
            char_array_4[3] = char_array_3[2] & 0x3f;

            for (i = 0; i < 4; i++)
                b64str[s++] = base64_chars[char_array_4[i]];

            i = 0;
        }
    }
    if (i) {
        for (j = i; j < 3; j++)
            char_array_3[j] = '\0';

        char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
        char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
        char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
        char_array_4[3] = char_array_3[2] & 0x3f;

        for (j = 0; j < i + 1; j++)
            b64str[s++] = base64_chars[char_array_4[j]];

        while (i++ < 3)
            b64str[s++] = '=';
    }
    b64str[b64len] = '\0';

    return b64str;
}

static inline bool is_base64(unsigned char c) {
    return (isalnum(c) || (c == '+') || (c == '/'));
}

static unsigned char *
    base64_decode(const char *input, int length, int *outlen)
{
    int i = 0;
    int j = 0;
    int r = 0;
    int idx = 0;
    unsigned char char_array_4[4], char_array_3[3];
    unsigned char *output = new unsigned char[length*3/4];

    while (length-- && input[idx] != '=') {
        //skip invalid or padding based chars
        if (!is_base64(input[idx])) {
            idx++;
            continue;
        }
        char_array_4[i++] = input[idx++];
        if (i == 4) {
            for (i = 0; i < 4; i++)
                char_array_4[i] = strchr(base64_chars, char_array_4[i]) - base64_chars;

            char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
            char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
            char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

            for (i = 0; (i < 3); i++)
                output[r++] = char_array_3[i];
            i = 0;
        }
    }

    if (i) {
        for (j = i; j <4; j++)
            char_array_4[j] = 0;

        for (j = 0; j <4; j++)
            char_array_4[j] = strchr(base64_chars, char_array_4[j]) - base64_chars;

        char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
        char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
        char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

        for (j = 0; (j < i - 1); j++)
            output[r++] = char_array_3[j];
    }

    *outlen = r;

    return output;
}


/**
 * This is the interface I added to these two convert functions, 
 *  that were originally written by Rene Nyffenegger.
 * Found them via google codesearch, specifically in
 *  http://jacksms.googlecode.com/svn/base64.cpp and
 *  http://jacksms.googlecode.com/svn/base64.hh
 * 2011, Ray Burgemeestre.
 */
#include <string>
#include <fstream>

using namespace std;

void display_usage(const char *programname)
{
    cerr << "Usage: " << programname << " [OPTION] [SOURCE] [DEST]" << endl
         << " where [OPTION] is either --to-base64 or --from-base64," << endl
         << "  [SOURCE] is the file to convert" << endl
         << "  [DEST] is the target/output file (will be overwritten)" << endl
         << "" << endl
         << "Examples: base64conv.exe --to-base64 somefile.exe somefile.txt" << endl
         << "          base64conv.exe --from-base64 somefile.txt somefile.exe" << endl
         << "(something like ./base64conv on linux)" << endl;
}

int main(int argc, char *argv[]) 
{
    enum Arguments { PROGRAM, OPTION, SOURCE, DEST, ARGS_LEN };
    if (argc != ARGS_LEN) {
        display_usage(argv[PROGRAM]);
        return -1;
    } else {
        char *sourcedata = NULL;
        ifstream::pos_type sourcedataLen = 0;
        ifstream sourcefile (argv[SOURCE], ios::in|ios::binary|ios::ate);
        if (sourcefile.is_open()) {
            sourcedataLen = sourcefile.tellg();
            sourcedata = new char [static_cast<int>(sourcedataLen)];
            sourcefile.seekg(0, ios::beg);
            sourcefile.read(sourcedata, sourcedataLen);
            sourcefile.close();
            cout << "source file " << argv[SOURCE] << " loaded" << endl;
        } else {
            cerr << "unable to open source file, " << argv[SOURCE] << endl;
            return -1;
        }

        if (strcmp(argv[OPTION], "--to-base64") == 0) {
            cout << "converting to base64" << endl;
            char *base64string = base64_encode(reinterpret_cast<unsigned char *>(sourcedata), 
                static_cast<int>(sourcedataLen));
            ofstream outputfile(argv[DEST], ios::out|ios::binary|ios::ate);
            if (outputfile.is_open()) {
                outputfile.write (base64string, strlen(base64string));
                outputfile.close();
                cout << "base64 string written to dest file, " << argv[DEST] << endl;
            } else {
                cerr << "unable to open dest file, ", argv[DEST];
                return -1;
            }
        }
        else if (strcmp(argv[OPTION], "--from-base64") == 0) {
            cout << "converting from base64" << endl;
            int outlen = 0;
            unsigned char *decodedbase64string= base64_decode(sourcedata, 
                static_cast<int>(sourcedataLen), &outlen);
            ofstream outputfile(argv[DEST], ios::out|ios::binary|ios::ate);
            if (outputfile.is_open()) {
                outputfile.write(reinterpret_cast<const char *>(decodedbase64string), outlen);
                outputfile.close();
                cout << "decoded base64 string written to dest file, " << argv[DEST] << endl;
            } else {
                cerr << "unable to open dest file, ", argv[DEST];
                return -1;
            }
        } else {
            display_usage(argv[PROGRAM]);
            cerr << "@@ invalid [OPTION] specified.";
            return -1;
        }
        delete[] sourcedata;
    }
}
C++ Comments (0)


Leave a Reply

Comment may not be visible immediately, because I process everything manually.**

**) I plan to automate this.., but it's on my ToDo since for ever..


Author:
Ray Burgemeestre
february 23th, 1984

Topics:
C++, Linux, Webdev

Other interests:
Music, Art, Zen