2014-04-04 55 views
1

我想使用C編碼base64和OpenSSL的字符串,稍後在C#中對其進行解碼。我有編碼下面的代碼:使用C和OpenSSL進行base64編碼

char *base64(const char *input, int length) { 
    BIO *bmem, *b64; 
    BUF_MEM *bptr; 

    b64 = BIO_new(BIO_f_base64()); 
    bmem = BIO_new(BIO_s_mem()); 
    b64 = BIO_push(b64, bmem); 
    BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); 
    BIO_write(b64, input, length); 
    BIO_flush(b64); 
    BIO_get_mem_ptr(b64, &bptr); 

    char *buff = (char *)malloc(bptr->length); 
    memcpy(buff, bptr->data, bptr->length-1); 
    buff[bptr->length-1] = 0; 

    BIO_free_all(b64); 

    return buff; 
} 

的問題是,當我在C#中對其進行解碼,我得到以下錯誤:

Invalid length for a Base-64 char array or string. 

搜索我發現,解碼後的字符串長度無效後我開始玩編碼的字符串,發現(在我看來)OpenSSL庫不會將新行\ n字符作爲單個換行符加密,而是作爲兩個單獨的符號進行加密。我的編碼錯了嗎,錯誤地考慮過換行符還是可以做其他事情?不要認爲需要另一個代碼片段,所以這是我粘貼的唯一代碼片段,但如果需要,將提供另一個代碼片段。

+0

不相關,但請不要投射'malloc'的返回指針 –

回答

2

問題是在

char *buff = (char *)malloc(bptr->length); 
memcpy(buff, bptr->data, bptr->length-1); 
buff[bptr->length-1] = 0; 

因爲,它留下比爲Base64少一個字節。

應該

char *buff = (char *)malloc(bptr->length+1); 
memcpy(buff, bptr->data, bptr->length); 
buff[bptr->length] = 0; 

這應該工作。