*}
codea teams

Base64 Encode



Encode a string with Base64 encoding. The return string must be freed.

char to_b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

char* b64enc(char *chunk, int chunkLen)
{
    int div = chunkLen / 3;
    int rem = chunkLen % 3;
    int chars = div*4 + rem + 1;
    char *buf;
    int newlines = (chars + CHARS_PER_LINE - 1) / CHARS_PER_LINE;

    char *data = chunk;

    char* string = (char*) malloc(chars + newlines + 2);
    memset(string, 0, sizeof string);

    if (string)
    {
        buf = string;
     
        chars = 0;

        while (div > 0)
        {
            buf[0] = to_b64[ (data[0] >> 2) & 0x3f];
            buf[1] = to_b64[((data[0] << 4) & 0x30) + ((data[1] >> 4) & 0xf)];
            buf[2] = to_b64[((data[1] << 2) & 0x3c) + ((data[2] >> 6) & 0x3)];
            buf[3] = to_b64[  data[2] & 0x3f];
            data += 3;
            buf += 4;
            div--;
            chars += 4;
            if (chars == CHARS_PER_LINE)
            {
                chars = 0;
                *(buf++) = '\n';
            }
        }

        switch (rem)
        {
        case 2:
            buf[0] = to_b64[ (data[0] >> 2) & 0x3f];
            buf[1] = to_b64[((data[0] << 4) & 0x30) + ((data[1] >> 4) & 0xf)];
            buf[2] = to_b64[ (data[1] << 2) & 0x3c];
            buf[3] = '=';
            buf += 4;
            chars += 4;
            break;
        case 1:
            buf[0] = to_b64[ (data[0] >> 2) & 0x3f];
            buf[1] = to_b64[ (data[0] << 4) & 0x30];
            buf[2] = '=';
            buf[3] = '=';
            buf += 4;
            chars += 4;
            break;
        }
        
        *buf = '\0';
    }
 
    return string;
}