使用libssl进行Bad Base64编码

ohe*_*ohe 2 c base64 openssl

假设以下代码,我的base64编码有奇怪的错误.

#include <openssl/bio.h>
#include <openssl/buffer.h>
#include <stdio.h>
#include <string.h>

char * base64(unsigned char * input, int length) {

    BIO *b64 = NULL;
    BIO * bmem = NULL;
    BUF_MEM *bptr = NULL;
    char * output = NULL;

    b64 = BIO_new((BIO_METHOD *)BIO_f_base64());
    BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
    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);

    output = (char *) calloc (bptr->length, sizeof(char));
    memcpy(output, bptr->data, bptr->length);

    BIO_free_all(b64);

    return output;
}


int main(int argc, char *argv[]) {


    char * based_string = NULL;

    based_string = base64(argv[1], strlen(argv[1]));
    printf("%s\n", based_string);
    free(based_string);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我用它编译它 gcc test.c -o test -lcrypto

如果我跑:

./test testtes

我有dGVzdHRlcw==?结果..而不是dGVzdHRlcw==

如果我跑:

./test test

我有dGVzdA==回报,这是好结果.

以前的源代码有什么问题.

Gra*_*rks 7

output = (char *) calloc (bptr->length + 1, sizeof(char));
Run Code Online (Sandbox Code Playgroud)

你错过了'+1',所以缓冲区中没有空格终止符.