2

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.

1
  • Unrelated, but please don't cast the return pointer of malloc Commented Apr 4, 2014 at 12:24

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.