Friday 22 January 2010

Howto base64 encode and decode with C and OpenSSL

The first here is how to base64 encode a chunk of memory using OpenSSL.
#include #include
#include
#include
#include
#include char *base64(const unsigned char *input, int length);

int main(int argc, char **argv)
{
char *output = base64(“YOYO!”, sizeof(“YOYO!”));
printf(“Base64: *%s*\n“, output);
free(output);
}

char *base64(const unsigned char *input, int length)
{
BIO *bmem, *b64;
BUF_MEM *bptr;

b64 = BIO_new(BIO_f_base64());
bmem = BIO_new(BIO_s_mem());
b64 = BIO_push(b64, bmem);
BIO_write(b64, input, length);
BIO_flush(b64);
BIO_get_mem_ptr(b64, &bptr);

char *buff = (char *)malloc(bptr->length);
memcpy(buff, bptr->data, bptr->length-1);
buff[bptr->length-1] = 0;

BIO_free_all(b64);

return buff;
}


base64 decode goes here:
#include
#include
#include
#include
#include
#include
char *unbase64(unsigned char *input, int length);int main(int argc, char **argv)
{
char *output = unbase64(“WU9ZTyEA\n“, strlen(“WU9ZTyEA\n“));
printf(“Unbase64: *%s*\n“, output);
free(output);
}

char *unbase64(unsigned char *input, int length)
{
BIO *b64, *bmem;

char *buffer = (char *)malloc(length);
memset(buffer, 0, length);

b64 = BIO_new(BIO_f_base64());
bmem = BIO_new_mem_buf(input, length);
bmem = BIO_push(b64, bmem);

BIO_read(bmem, buffer, length);

BIO_free_all(bmem);

return buffer;
}

You can visit my second blog : devenix.wordpress.com

No comments:

Post a Comment