Crypto openssl library - base64 conversion

I am using opensl BIO objects to convert a binary string to a base64 string. The code is as follows:

void ToBase64(std::string & s_in) { BIO * b_s = BIO_new( BIO_s_mem() ); BIO * b64_f = BIO_new( BIO_f_base64() ); b_s = BIO_push( b64_f , b_s); std::cout << "IN::" << s_in.length(); BIO_write(b_s, s_in.c_str(), s_in.length()); char * pp; int sz = BIO_get_mem_data(b_s, &pp); std::cout << "OUT::" << sz << endl; s_in.assign(pp,sz); //std::cout << sz << " " << std::string(pp,sz) << std::endl; BIO_free (b64_f); // TODO ret error potential BIO_free (b_s); // } 

The length is either 64 or 72. However, the output is always 65, which is incorrect, it should be much larger. The documentation is not the best in the world, AFAIK bio_s_mem object should grow dynamically. What am I doing wrong?

I'm probably better off finding a standalone C ++ class that doesn't offer streaming support and supports base64 conversions. Streaming support is not suitable for my application. However, I just wanted to stick with openSSL, since I'm already depending on some crypto options. In any case, I will make such a decision after profiling.

+4
source share
2 answers

You have two problems:

  • You need to call BIO_get_mem_data() in mem mem, but you have lost the link to it (you are overwriting it with the return value from BIO_push , which is equal to b64_f ).
  • You should call BIO_flush() in the base64 BIOS after you have written all your data.
+2
source

I think you want to reorder the arguments in BIO_push.

b_s = BIO_push (b_s, b64_f)

0
source

Source: https://habr.com/ru/post/1305754/


All Articles