Click here to Skip to main content
14,930,671 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I want to convert RSA encrypted message to Base64 format inorder to send encrypted message via TCP/IP socket as a character buffer.

How to do the Base64 encoding in C program ??? Shed some bright light :-)

Thanks in advance.
Posted

Have a little patience! You only posted this eight minutes ago, and you repost it with less information already?
   
Comments
Tarun.K.S 20-Apr-11 8:23am
   
This could have been written as a comment.
OriginalGriff 20-Apr-11 8:29am
   
Yes, but posting it as a reply removes it from the unanswered list without deleting it.
Base64 encoding is very simple, you should complete the encoding routine in half a hour, after reading some documentation. As starting point see Base64 at Wikipedia[^].
   
This is what you want (in C++):

C#
static const std::string base64_chars =  "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                                         "abcdefghijklmnopqrstuvwxyz"
                                         "0123456789+/";


std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len)
{
    std::string ret;
    int i = 0;
    int j = 0;
    unsigned char char_array_3[3];
    unsigned char char_array_4[4];

    while (in_len--) {
        char_array_3[i++] = *(bytes_to_encode++);
        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++) ret += 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++) ret += base64_chars[char_array_4[j]];

        while((i++ < 3)) ret += '=';
    }

    return ret;
}


Hope it helps
   
Comments
rprtech 21-Apr-11 4:14am
   
Hi Thanks for your reply. But I am having one small doubt on program.
where is that base64_chars[] array is defined??? The program gives compilation error here.
Is it any predefined fn in c++. Bcoz I am converting to C program.

Pls explain.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900