Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

base64 decode not working

Tags:

c

openssl

base64

I have the following code:

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

which doesn't show the decoded string.

base64 encoding is working just fine, so what am I doing wrong?

Edit: found the answer ... base64 decoding requires '\n'

like image 770
Sam Reina Avatar asked Mar 16 '26 05:03

Sam Reina


1 Answers

The OpenSSL API is dreadful to use, so I commend you on your insanity. Regardless, as you've eluded to in-comment, the decoder requires a newline unless you specifically tell it otherwise, which the code below does:

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

Run against your data, the following is the result

original: this is a test string

Yeah, because that's intuitive.

like image 87
WhozCraig Avatar answered Mar 17 '26 19:03

WhozCraig



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!