Created
December 12, 2020 14:32
-
-
Save juergenhoetzel/1a4ecd86648f8e571fb090a6e1c6dc40 to your computer and use it in GitHub Desktop.
Base64 encoding and decoding using OpenSSL
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
// 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; | |
} |
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
Based on OpenSSL Base64 Encoding: Binary Safe and Portable
Changes: