2014-05-15 2 views
0

이 내가 함수를 호출하는 방법입니다거짓 출력 : 기본 C 64 디코딩

/* Macro definitions */ 
     #define TABLELEN  63 
     #define BUFFFERLEN  128 

     #define ENCODERLEN  4 
     #define ENCODEROPLEN 0 
     #define ENCODERBLOCKLEN 3 

     #define PADDINGCHAR  '=' 
     #define BASE64CHARSET "ABCDEFGHIJKLMNOPQRSTUVWXYZ"\ 
           "abcdefghijklmnopqrstuvwxyz"\ 
           ""\ 
           "+/"; 


    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; 
    } 

(나는 인터넷에서 디코딩 기능을 발견) :

char decodedstring[10]; 
ha = Base64Decode(authTable[0]->AuthenticationCred[k].userpassb64,decodedstring, outlen); 
*userId = strtok(decodedstring, ":"); 

코드 실행을하지만, 출력은 false입니다. 출력은 username : password 여야합니다. 그러나이 경우 출력은 \ 006 \ busername : password입니다. 사용자 이름을 디코딩 된 문자열에서 추출해야합니다. 사용자 이름 앞에 추가 문자가 있기 때문에 작동하지 않습니다.

함수에 문제가 있습니까? 아니면 초 기자에게 여분의 문자를 가져 오는 이유는 무엇입니까?

+0

입력 내용은 무엇입니까? 그것없이 출력이 정확한지 알 수있는 방법이 없습니다. –

+0

그건 그렇고, 당신이 발견 한 코드는 버그가 있습니다 : 디코딩 된 출력에 null이 있다면? strncat은 그 이상으로 복사하지 않습니다. 다른 문제도 있습니다. 더 나은 구현 방법 찾기 : 몇 가지 다른 방법이 있습니다. –

답변

1

디코더가 올바르게 작동하지만 출력 버퍼를 초기화하지 않은 것이 문제입니다. 디코더는 항상 strncat 함수를 사용하여 출력 문자를 추가합니다. 출력 버퍼에 statup에서 가비지 값이있을 수 있으므로 실제 디코드 된 값이 가비지 값에 추가됩니다. 사용하기 전에 출력 버퍼를 초기화하는 memset을 추가하면 모든 것이 잘 동작합니다. 또한 주석에서 Gil Hamilton이 언급 한 것처럼이 디코더는 텍스트 출력에만 사용되며 바이너리 출력을 디코딩하면 오류가 발생합니다.

char decodedstring[30]; 
memset(&decodedstring[0], 0, 30); 
ha = Base64Decode(authTable[0]->AuthenticationCred[k].userpassb64,decodedstring, outlen); 
*userId = strtok(decodedstring, ":");