[英]base64 decode not working
我有以下代碼:
char *encoded = "dGhpcyBpcyBhIHRlc3Qgc3RyaW5n";
char *unbase = unbase64(encoded,strlen(encoded));
printf("original: %s\n",unbase);
free(unbase);
char *unbase64(unsigned char *input,int length)
{
BIO *b64,*bmem;
char *buff = (char *)malloc(length);
b64 = BIO_new(BIO_f_base64());
bmem = BIO_new_mem_buf(input,length);
bmem = BIO_push(b64,bmem);
BIO_read(bmem,buff,length);
BIO_free_all(bmem);
return buff;
}
char *base64(const unsigned char *input,int length)
{
BIO *bmem,*b64 = NULL;
BUF_MEM *bptr;
b64 = BIO_new(BIO_f_base64());
bmem = BIO_new(BIO_s_mem());
b64 = BIO_push(b64,bmem);
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;
}
它沒有顯示解碼的字符串。
base64編碼工作得很好,所以我做錯了什么?
編輯:找到答案... base64解碼需要'\\ n'
OpenSSL API使用起來很糟糕,所以我贊揚你的瘋狂。 無論如何,正如你在評論中所說的那樣,解碼器需要一個換行符,除非你明確告訴它,下面的代碼如下:
char *unbase64(void *input, int length)
{
char *res = malloc(length);
BIO *bmem = BIO_new_mem_buf(input, length);
BIO *b64 = BIO_new(BIO_f_base64());
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
bmem = BIO_push(b64, bmem);
long n = BIO_read(bmem, res, length);
if (n > 0)
res[n] = 0;
else
res[0] = 0; // note: this is an error state.
BIO_free_all(bmem);
return res;
}
針對您的數據運行,結果如下
original: this is a test string
是的,因為這很直觀。
內存分配不足
// char *buff = (char *)malloc(length);
char *buff = (char *)malloc(length + 1);
// may also need
buff[length] = '\0';
懷疑其他問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.