Skip to content

Instantly share code, notes, and snippets.

@Valken
Created May 2, 2016 09:53
Show Gist options
  • Save Valken/8f9b6266a7f521c0c92d95c1f7b8c7ae to your computer and use it in GitHub Desktop.
Save Valken/8f9b6266a7f521c0c92d95c1f7b8c7ae to your computer and use it in GitHub Desktop.
#include "Encode.h"
#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/buffer.h>
std::string Base64Encode(uint8_t const* input, size_t length)
{
BIO *b64 = BIO_new(BIO_f_base64());
BIO *mem = BIO_new(BIO_s_mem());
mem = BIO_push(b64, mem);
//BIO_set_flags(mem, BIO_FLAGS_BASE64_NO_NL);
BIO_write(mem, input, length);
BIO_flush(mem);
BUF_MEM *buffer = nullptr;
BIO_get_mem_ptr(mem, &buffer);
char *data = new char[buffer->length];
memcpy(data, buffer->data, buffer->length - 1);
data[buffer->length - 1] = 0;
std::string output(data);
BIO_free_all(mem);
return output;
}
void Base64Decode(std::string const& input, uint8_t* output, size_t outputSize)
{
// https://www.openssl.org/docs/manmaster/crypto/bio.html
// https://www.openssl.org/docs/manmaster/crypto/BIO_f_base64.html
BIO *b64 = BIO_new(BIO_f_base64());
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
auto data = const_cast<char *>(input.c_str());
auto size = input.size();
BIO *memoryBuffer = BIO_new_mem_buf(data, size);
// https://www.openssl.org/docs/manmaster/crypto/BIO_push.html
// Chain is b64 - memoryBuffer. Writing to it encodes to base64, reading decodes.
memoryBuffer = BIO_push(b64, memoryBuffer);
int read = BIO_read(memoryBuffer, output, outputSize);
BIO_free_all(memoryBuffer);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment