I\'ve been trying to figure out the openssl documentation for base64 decoding and encoding. I found some code snippets below
Here is an example of OpenSSL base64 encode/decode I wrote:
Notice, I have some macros/classes in the code that I wrote, but none of them is important for the example. It is simply some C++ wrappers I wrote:
buffer base64::encode( const buffer& data )
{
// bio is simply a class that wraps BIO* and it free the BIO in the destructor.
bio b64(BIO_f_base64()); // create BIO to perform base64
BIO_set_flags(b64,BIO_FLAGS_BASE64_NO_NL);
bio mem(BIO_s_mem()); // create BIO that holds the result
// chain base64 with mem, so writing to b64 will encode base64 and write to mem.
BIO_push(b64, mem);
// write data
bool done = false;
int res = 0;
while(!done)
{
res = BIO_write(b64, data.data, (int)data.size);
if(res <= 0) // if failed
{
if(BIO_should_retry(b64)){
continue;
}
else // encoding failed
{
/* Handle Error!!! */
}
}
else // success!
done = true;
}
BIO_flush(b64);
// get a pointer to mem's data
char* dt;
long len = BIO_get_mem_data(mem, &dt);
// assign data to output
std::string s(dt, len);
return buffer(s.length()+sizeof(char), (byte*)s.c_str());
}