tags:

views:

75

answers:

1

Assuming the following code, i have strange error in my base64 encodings.

#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;
}

I compile it with gcc test.c -o test -lcrypto

if I run :

./test testtes

I have dGVzdHRlcw==� in result.. instead of dGVzdHRlcw==

if I run :

./test test

I have dGVzdA== in return, which is the good result.

What's wrong with the previous source code.

+5  A: 
output = (char *) calloc (bptr->length + 1, sizeof(char));

You're missing the '+1', so there's no room in the buffer for the null-terminator.

Graham Perks
I'm a little ashamed for not having seen this problem. Thanks a lot
ohe