Question

I'm trying to encode a string with base64 and OpenSSL in C and decode it in C# later. I have the following code for encoding:

char *base64(const char *input, int length) {
    BIO *bmem, *b64;
    BUF_MEM *bptr;

    b64 = BIO_new(BIO_f_base64());
    bmem = BIO_new(BIO_s_mem());
    b64 = BIO_push(b64, bmem);
    BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
    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;
}

The problem is that when I decode it in C# I get the following error:

Invalid length for a Base-64 char array or string.

After searching I found that the decoded string is of invalid length and I started playing with the encoded string and found that (in my opinion) the OpenSSL library does not encrypt the newline \n character as a single, newline character, but as a two separate symbols. Am I encoding it wrong, got wrong thought about the newline character or is it possible to be anything else? Don't think there is another code snippet required so this is the only one I've pasted, but will provide another if necessary.

Was it helpful?

Solution

Problem is at

char *buff = (char *)malloc(bptr->length);
memcpy(buff, bptr->data, bptr->length-1);
buff[bptr->length-1] = 0;

Because, it leaves one byte less than in Base64.

It should be

char *buff = (char *)malloc(bptr->length+1);
memcpy(buff, bptr->data, bptr->length);
buff[bptr->length] = 0;

This should work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top