c - base64 decode not working -


i have 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 decoded string.

base64 encoding working fine, doing wrong?

edit: found answer ... base64 decoding requires '\n'

the openssl api dreadful use, commend on insanity. regardless, you've eluded in-comment, decoder requires newline unless tell otherwise, 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: error state.      bio_free_all(bmem);      return res; } 

run against data, following result

original: test string 

yeah, because that's intuitive.


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -