Skip to content

Instantly share code, notes, and snippets.

@zno5
Created August 20, 2016 13:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zno5/eff2b659bf29d780200a779e9b3cda81 to your computer and use it in GitHub Desktop.
Save zno5/eff2b659bf29d780200a779e9b3cda81 to your computer and use it in GitHub Desktop.
Encode Base64 with OpenSSL 1.0.2h
#include <cstdint>
#include <string>
#include <vector>
#include <openssl/evp.h>
#include <openssl/buffer.h>
namespace {
bool EncodeBase64(std::string & out, const std::vector<uint8_t> & in)
{
if (INT_MAX < in.size())
{
return false;
}
auto bio = BIO_new(BIO_s_mem());
if (!bio)
{
return false;
}
auto b64 = BIO_new(BIO_f_base64());
if (!b64)
{
BIO_free(bio);
return false;
}
BIO_push(b64, bio);
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
auto size = static_cast<int>(in.size());
auto writeBytes =
BIO_write(b64, static_cast<const void *>(in.data()), size);
if (0 >= writeBytes)
{
BIO_free_all(b64);
return false;
}
if (BIO_flush(b64) != 1)
{
BIO_free_all(b64);
return false;
}
BUF_MEM * bptr = nullptr;
if (BIO_get_mem_ptr(b64, &bptr) != 1)
{
BIO_free_all(b64);
return false;
}
out.assign(bptr->data, bptr->length);
BIO_free_all(b64);
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment