Hi All,

I am doing Base64 encoding and decoding of a string "testencoding" using OpenSSL api *BIO_f_base64, *but when Base64 encoding is done for the same string using OpenSSL command *base64,* the last byte of encoded data will be different than the one generated using *BIO_f_base64 *api.
Also the Base64 decoding api returns NULL. The code snippet is as follows:
_
Encoding of string "*testencoding*" using *base64* command:_

*#base64 data.txt > encode.txt*
   data.txt -----> It contains only the string "*testencoding*"
   encode.txt -----> It contains encoded data
*#cat encode.txt
dGVzdGVuY29kaW5nCg==

*_Encoding of string "*testencoding*" using *BIO_f_base64* api:
_
char str[]="testencoding";
char *ptr;

ptr=base64(str, strlen(str));
printf("Encoded string = %s\n", ptr);
char *base64(const char *input, int32_t length)
{
  BIO *bmem=NULL, *b64=NULL;
  char *buff;
  BUF_MEM *bptr;
  b64 = (BIO *)BIO_new(BIO_f_base64());
  bmem = (BIO *)BIO_new(BIO_s_mem());
  b64 = (BIO *)BIO_push(b64, bmem);
  BIO_write(b64, input, length);
  BIO_flush(b64);
  BIO_get_mem_ptr(b64, &bptr);
  buff = (char *)malloc(bptr->length+1);
  memcpy(buff, bptr->data, bptr->length);
  buff[bptr->length] = 0;
  if(b64)
  BIO_free_all(b64);
   return buff;
 }

The output of the above code snippet is : *dGVzdGVuY29kaW5n*

_
Decoding of same encoded text* "*_*_dGVzdGVuY29kaW5nCg==" _*_using_*_ Base64 _*_openssl command:
_*#base64 -d encode.txt > decode.txt*
   encode.txt -----> It contains encoded data
   decode.txt -----> It contains decoded data
*#cat decode.txt
testencoding

*_Decoding of same encoded text_*_ "_*_*dGVzdGVuY29kaW5nCg" *using* openssl api's:

*_*char *unbase64(unsigned char *input, int length)
* {
    BIO *b64=NULL, *bmem=NULL;
    FILE *ptr;
    char *buffer = (char *)malloc(length);
    memset(buffer,0,length);
    b64 = (BIO *)BIO_new(BIO_f_base64());
    bmem = BIO_new_mem_buf(input, length);
    bmem = (BIO *)BIO_push(b64, bmem);
    BIO_read(bmem, buffer,length);
    if(bmem)
        BIO_free_all(bmem);
    return buffer;
}

When encoded data " *dGVzdGVuY29kaW5nCg" *is passed to the above function, it returns NULL.

Please let me know why* BIO_read *is returning NULL on decoding and also why the last bytes of encoded data(using OpenSSL api) is different than the encoded data using openssl command.

Thanks & Best Regards,
Vinay

_*
*_

Reply via email to