3

我有以下代码:

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'

4

2 回答 2

2

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

是的,因为这很直观。

于 2013-09-24T19:24:12.517 回答
0

内存分配不足

// char *buff = (char *)malloc(length);
char *buff = (char *)malloc(length + 1);
// may also need
buff[length] = '\0';

怀疑其他问题。

于 2013-09-24T18:09:24.233 回答