#include <stdlib.h>
#include <string.h>
#include "../include/binary.h"
#ifdef OPENSSL
#include "openssl/pem.h"
#endif
binary_t* instantiate_binary_t(char* data, int len) {
binary_t* ret = malloc(sizeof(struct binary_t));
ret->len=len;
ret->data = malloc(len);
memcpy(ret->data, data, len);
return ret;
}
char *base64encode (const void *b64_encode_this, int encode_this_many_bytes){
#ifdef OPENSSL
BIO *b64_bio, *mem_bio;
BUF_MEM *mem_bio_mem_ptr;
b64_bio = BIO_new(BIO_f_base64());
mem_bio = BIO_new(BIO_s_mem());
BIO_push(b64_bio, mem_bio);
BIO_set_flags(b64_bio, BIO_FLAGS_BASE64_NO_NL);
BIO_write(b64_bio, b64_encode_this, encode_this_many_bytes);
BIO_flush(b64_bio);
BIO_get_mem_ptr(mem_bio, &mem_bio_mem_ptr);
BIO_set_close(mem_bio, BIO_NOCLOSE);
BIO_free_all(b64_bio);
BUF_MEM_grow(mem_bio_mem_ptr, (*mem_bio_mem_ptr).length + 1);
(*mem_bio_mem_ptr).data[(*mem_bio_mem_ptr).length] = '\0';
return (*mem_bio_mem_ptr).data;
#else
#warning Data will not be encoded. If you want to use function "base64encode", please define "-DOPENSSL" when building the library.
return NULL;
#endif
}
char *base64decode (const void *b64_decode_this, int decode_this_many_bytes, int *decoded_bytes){
#ifdef OPENSSL
BIO *b64_bio, *mem_bio;
char *base64_decoded = calloc( (decode_this_many_bytes*3)/4+1, sizeof(char) );
b64_bio = BIO_new(BIO_f_base64());
mem_bio = BIO_new(BIO_s_mem());
BIO_write(mem_bio, b64_decode_this, decode_this_many_bytes);
BIO_push(b64_bio, mem_bio);
BIO_set_flags(b64_bio, BIO_FLAGS_BASE64_NO_NL);
int decoded_byte_index = 0;
while ( 0 < BIO_read(b64_bio, base64_decoded+decoded_byte_index, 1) ){
decoded_byte_index++;
}
BIO_free_all(b64_bio);
*decoded_bytes = decoded_byte_index;
return base64_decoded;
#else
#warning Data will not be decoded. If you want to use function "base64decode", please define "-DOPENSSL" when building the library.
return NULL;
#endif
}