2014-05-15 28 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, ":"); 

的代碼運行,但輸出是錯誤的。 輸出應該是:用戶名:密碼。但在這種情況下,輸出是\ 006 \ busername:密碼。 我需要從decodedstring中提取用戶名。由於用戶名之前的額外字符,它不起作用。

該函數有什麼問題,或者爲什麼我會在開始時獲得這些額外的char-s?

+0

什麼是輸入?沒有辦法告訴你的輸出是否正確。 –

+0

順便說一句,你發現的代碼有錯誤:如果在解碼輸出中有一個空值怎麼辦? 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, ":");