pf85
pf85

Reputation: 195

Am I properly base64-encoding a buffer with OpenSSL?

I have this buffer given:

unsigned char *buffer; 
int buffer_length; 

This is how I currently convert it to a base64-encoded buffer:

BIO *mem = BIO_new(BIO_s_mem()); 
BIO *b64 = BIO_new(BIO_f_base64()); 
mem = BIO_push(b64, mem); 

int write_length = BIO_write(mem, buffer, buffer_length); 
if (write_length != buffer_length) //* 
  return -1; 

int flush_result = BIO_flush(mem); 
if (flush_result != 1) 
  return -1; 

unsigned char *result; //** 
int result_length = BIO_get_mem_data(mem, &result); 

//use the base64-encoded result to do whatever I need to do 

BIO_free_all(mem); 
return 0;

So far, this seems to be working. However, is this good and robust code? I have particular questions about the code pieces marked with asterisks above:

Upvotes: 4

Views: 664

Answers (1)

Francis Upton IV
Francis Upton IV

Reputation: 19443

//* You should put your BIO_write() in a loop. The man page is pretty clear about that (that it attempts to write the requested number of bytes), and that's consistent with the other write stuff in C.

//** You should use char * since that's what the man page specifies, though I'm not sure that's a big deal.

Upvotes: 1

Related Questions