Skip to content

Instantly share code, notes, and snippets.

@juergenhoetzel
Created December 12, 2020 14:32
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 juergenhoetzel/1a4ecd86648f8e571fb090a6e1c6dc40 to your computer and use it in GitHub Desktop.
Save juergenhoetzel/1a4ecd86648f8e571fb090a6e1c6dc40 to your computer and use it in GitHub Desktop.
Base64 encoding and decoding using OpenSSL
// Encodes Base64
#include <openssl/bio.h>
#include <openssl/buffer.h>
#include <openssl/evp.h>
#include <stdint.h>
// Decodes Base64
#include <assert.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
/* must be freed by caller */
char *base64_decode(char *b64message, int *dst_len) {
BIO *bmem = BIO_new(BIO_s_mem());
BIO *b64 = BIO_new(BIO_f_base64());
BUF_MEM *buf_mem;
BIO_push(b64, bmem);
BIO_puts(b64, b64message);
BIO_flush(b64);
BIO_get_mem_ptr(bmem, &buf_mem);
BIO_set_close(bmem, BIO_NOCLOSE);
BIO_free_all(b64);
*dst_len = buf_mem->length;
return strndup(buf_mem->data, buf_mem->length);
}
char *base64_encode(const char *buffer, size_t buffer_len) {
BIO *bmem = BIO_new(BIO_s_mem());
BIO *b64 = BIO_new(BIO_f_base64());
BUF_MEM *buf_mem;
b64 = BIO_new(BIO_f_base64());
bmem = BIO_new(BIO_s_mem());
BIO_push(bmem, b64);
BIO_write(bmem, buffer, buffer_len);
BIO_flush(bmem);
BIO_get_mem_ptr(b64, &buf_mem);
BIO_set_close(b64, BIO_NOCLOSE);
BIO_free_all(b64);
return strndup(buf_mem->data, buffer_len);
}
int main() {
// Encode To Base64
char *base64_encode_output, *text = "pas1";
base64_encode_output = base64_encode(text, strlen(text));
printf("Output (base64): %s\n", base64_encode_output);
// Decode From Base64
int len;
char *base64_decode_output = base64_decode("SGVsbG8gV29ybGQ=", &len);
printf("Output: %s\n", base64_decode_output);
return 0;
}
@juergenhoetzel
Copy link
Author

Based on OpenSSL Base64 Encoding: Binary Safe and Portable

Changes:

  • simplefied API
  • no need to manually calculate output length

@teplofizik
Copy link

Duplicated new in base64_encode:

  b64 = BIO_new(BIO_f_base64());
  bmem = BIO_new(BIO_s_mem());

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment