hope this helps. i don't remember where i found it...
any way, here you are.
#include stdio.h
#include base64.h
unsigned char alphabet[64] = ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/;
int
base64_decode(unsigned char *outbuf, unsigned char *inbuf, int size)
{
static unsigned char inalphabet[256], decoder[256];
int j, i, bits, c, char_count, errors = 0;
for (i = (sizeof alphabet) - 1; i = 0 ; i--) {
inalphabet[alphabet[i]] = 1;
decoder[alphabet[i]] = i;
}
char_count = 0;
bits = 0;
i = 0;
j = 0;
while (isize) {
c = inbuf[i++];
if (c == '=') break;
if (c 255 || ! inalphabet[c]) continue;
bits += decoder[c];
char_count++;
if (char_count == 4) {
outbuf[j++] = bits 16;
outbuf[j++] = (bits 8) 0xff;
outbuf[j++] = bits 0xff;
bits = 0;
char_count = 0;
} else {
bits = 6;
}
}
if (c == EOF) {
if (char_count) errors++;
} else { /* c == '=' */
switch (char_count) {
case 1:
errors++;
break;
case 2:
outbuf[j++] = bits 10;
break;
case 3:
outbuf[j++] = bits 16;
outbuf[j++] = (bits 8) 0xff;
break;
}
}
return (errors ? 0 : j);
}
int
base64_encode(unsigned char *outbuf, unsigned char *inbuf, int size)
{
int i, j, cols, bits, c, char_count;
char_count = 0;
bits = 0;
cols = 0;
i = 0;
j = 0;
while (isize) {
c = inbuf[i++];
bits += c;
char_count++;
if (char_count == 3) {
outbuf[j++] = alphabet[bits 18];
outbuf[j++] = alphabet[(bits 12) 0x3f];
outbuf[j++] = alphabet[(bits 6) 0x3f];
outbuf[j++] = alphabet[bits 0x3f];
cols += 4;
if (cols == 72) {
outbuf[j++] = '\n';
cols = 0;
}
bits = 0;
char_count = 0;
} else {
bits = 8;
}
}
if (char_count != 0) {
bits = 16 - (8 * char_count);
outbuf[j++] = alphabet[bits 18];
outbuf[j++] = alphabet[(bits 12) 0x3f];
if (char_count == 1) {
outbuf[j++] = '=';
outbuf[j++] = '=';
} else {
outbuf[j++] = alphabet[(bits 6) 0x3f];
outbuf[j++] = '=';
}
if (cols 0) outbuf[j++] = '\n';
}
return j;
}