Reputation: 309
(I found the decoding function on the internet)
/* Macro definitions */
#define TABLELEN 63
#define BUFFFERLEN 128
#define ENCODERLEN 4
#define ENCODEROPLEN 0
#define ENCODERBLOCKLEN 3
#define PADDINGCHAR '='
#define BASE64CHARSET "ABCDEFGHIJKLMNOPQRSTUVWXYZ"\
"abcdefghijklmnopqrstuvwxyz"\
"0123456789"\
"+/";
int decodeblock(char *input, char *output, int oplen){
int rc = 0;
char decodedstr[ENCODERLEN + 1] = "";
decodedstr[0] = input[0] << 2 | input[1] >> 4;
decodedstr[1] = input[1] << 4 | input[2] >> 2;
decodedstr[2] = input[2] << 6 | input[3] >> 0;
strncat(output, decodedstr, oplen-strlen(output));
return rc;
}
int Base64Decode(char *input, char *output, int oplen){
char *charval = 0;
char decoderinput[ENCODERLEN + 1] = "";
char encodingtabe[TABLELEN + 1] = BASE64CHARSET;
int index = 0, asciival = 0, computeval = 0, iplen = 0, rc = 0;
iplen = oplen;
while(index < iplen){
asciival = (int)input[index];
if(asciival == PADDINGCHAR){
rc = decodeblock(decoderinput, output, oplen);
break;
}else{
charval = strchr(encodingtabe, asciival);
if(charval){
decoderinput[computeval] = charval - encodingtabe;
computeval = (computeval + 1) % 4;
if(computeval == 0){
rc = decodeblock(decoderinput, output, oplen);
decoderinput[0] = decoderinput[1] =
decoderinput[2] = decoderinput[3] = 0;
}
}
}
index++;
}
return rc;
}
This is how I call the function:
char decodedstring[10];
ha = Base64Decode(authTable[0]->AuthenticationCred[k].userpassb64,decodedstring, outlen);
*userId = strtok(decodedstring, ":");
The code runs, but the output is false. The output should be: username:password. But in this case the output is \006\busername:password. I need to extract the username from decodedstring. Because of the extra characters before the username it doesn't work.
Is something wrong with the function or why do I get those extra char-s at the begnning?
Upvotes: 0
Views: 53
Reputation: 21
The decoder works correctly, the issue is you have not initialized your output buffer. The decoder always uses the strncat function to append the output character. Your output buffer might have a garbage value at statup, so the actual decoded value is appended to the garbage value. Add a memset to initialize your output buffer before usage, everything should work fine. And also as mentioned by Gil Hamilton in the comment this decoder works only for text outputs, trying to decode for binary outputs will lead to error.
char decodedstring[30];
memset(&decodedstring[0], 0, 30);
ha = Base64Decode(authTable[0]->AuthenticationCred[k].userpassb64,decodedstring, outlen);
*userId = strtok(decodedstring, ":");
Upvotes: 1