Hi , I am currently trying to implement base64 encoding and decoding scheme in C . Python has a module , base64 , that will do the encoding and decoding with ease . I am aware of OpenSSL having support for base64 encoding and decoding , but i will have to now implement both in C without using the openssl libraries .
I was able to download a code w.r.t. base 64 encoding and decoding . I am attaching the code below . void encodeblock( unsigned char cin[3], unsigned char cout[4], int nlen ) { cout[0] = cb64[ cin[0] >> 2 ]; cout[1] = cb64[ ((cin[0] & 0x03) << 4) | ((cin[1] & 0xf0) >> 4) ]; cout[2] = (unsigned char) (nlen > 1 ? cb64[ ((cin[1] & 0x0f) << 2) | ((cin[2] & 0xc0) >> 6) ] : '='); cout[3] = (unsigned char) (nlen > 2 ? cb64[ cin[2] & 0x3f ] : '='); } void decodeblock( unsigned char cin[4], unsigned char cout[3] ) { cout[ 0 ] = (unsigned char ) (cin[0] << 2 | cin[1] >> 4); cout[ 1 ] = (unsigned char ) (cin[1] << 4 | cin[2] >> 2); cout[ 2 ] = (unsigned char ) (((cin[2] << 6) & 0xc0) | cin[3]); } int base641_decodestring(char* pcstr,int size,char** ppcdest) { unsigned char cin[4] = {""}; unsigned char cout[3] = {""}; unsigned char cv = 0; int ni = 0; int nlen = 0; char* cptr = pcstr; *ppcdest = malloc(sizeof(char)*160); if (!*ppcdest) { return 1; } memset(*ppcdest,0,sizeof(char)*160); char* pcstring = malloc( sizeof(char) * SIZE); if (!pcstring) { aps_log("APS_log.txt","\nbae64.c:base64encode:malloc failed \n"); return 1; } memset(pcstring,'\0',SIZE); for( nlen = 0, ni = 0; ni < 4; ni++ ) { cv = 0; while( cv == 0 ) { cv = (unsigned char) *cptr; cv = (unsigned char) ((cv < 43 || cv > 122) ? 0 : cd64[ cv - 43 ]); if( cv ) { cv = (unsigned char) ((cv == '$') ? 0 : cv - 61); } } if( cptr++ ) { nlen++; if( cv ) { cin[ ni ] = (unsigned char) (cv - 1); } } else { cin[ni] = 0; } } if( nlen ) { decodeblock( cin, cout ); } memcpy(*ppcdest,cout,160); return 0; }/*end of base64_decode */ char* base64_encode(char* pcstr) { unsigned char cin[3] = {""}; unsigned char cout[4] = {""}; int ni = 0; int nlen = 0; int flag = 1; char* cptr = pcstr; char* pcstring = malloc( sizeof(char) * SIZE); if (!pcstring) { aps_log("APS_log.txt","\nbae64.c:base64encode:malloc failed \n"); return (void*)0; } memset(pcstring,'\0',SIZE); while( flag ) { for( ni = 0; ni < 3; ni++ ) { cin[ni] = (unsigned char)*cptr; if( *++cptr != '\0' ) nlen++; else { cin[ni] = 0; flag = 0; break; } } encodeblock(cin, cout,nlen); strcat(pcstring,cout); } return pcstring; }/* end of base64_encode */ But this code gives different hex values as compared to the python base64.encodestring and base64.decodestring respectively . I need some help on this matter . I need some pointers on where is the mistake for the above file . -- http://mail.python.org/mailman/listinfo/python-list