Skip to content

Instantly share code, notes, and snippets.

@scraimer
Created October 17, 2018 09:05
Show Gist options
  • Save scraimer/7b7686f3b8e81480d5404ac4c004b168 to your computer and use it in GitHub Desktop.
Save scraimer/7b7686f3b8e81480d5404ac4c004b168 to your computer and use it in GitHub Desktop.
Use OpenSSL BIO chain to read a base64-encoded file and write the decoded binary to a file
#include <string>
#include <cstring>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <openssl/bio.h>
//#include <openssl/bytestring.h>
#include <openssl/crypto.h>
//#include <openssl/digest.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/rsa.h>
#include <openssl/x509.h>
#include <fstream>
#include <sstream>
using namespace std;
//##################################################################################################
void go()
{
BIO * infile = BIO_new_file( "signature.base64", "r" );
BIO * base64 = BIO_new( BIO_f_base64() );
BIO * in_chain = infile;
in_chain = BIO_push( base64, in_chain );
BIO * outfile = BIO_new_file( "signature.binary", "w" );
BIO * out_chain = outfile;
int const buffer_len = 1024;
char buffer[ buffer_len ];
int bytes_read = BIO_read( in_chain, buffer, buffer_len );
while( bytes_read > 0 )
{
int const bytes_written = BIO_write( out_chain, buffer, bytes_read );
if( bytes_written <= 0 )
{
stringstream msg;
msg << "Error writing to output chain. BIO_write returned " << bytes_written;
throw runtime_error( msg.str() );
}
bytes_read = BIO_read( in_chain, buffer, buffer_len );
}
cout << "Final result: " << bytes_read << "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment