我有以下代码:
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'
答案 0 :(得分:1)
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
是的,因为 直观。
答案 1 :(得分:0)
内存分配不足
// char *buff = (char *)malloc(length);
char *buff = (char *)malloc(length + 1);
// may also need
buff[length] = '\0';
怀疑其他问题。