Created
August 20, 2016 13:09
-
-
Save zno5/eff2b659bf29d780200a779e9b3cda81 to your computer and use it in GitHub Desktop.
Encode Base64 with OpenSSL 1.0.2h
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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