Tue 11 Apr 2006
I've been doing a little C programming lately and I have found that if you have a up to date distribution of linux there are a lot of libraries out there that make doing things you do in other languages like java easier.
As I have time I'm going to post some examples of what I have found. The first here is how to base64 encode a chunk of memory using OpenSSL.
#include <openssl/sha.h>
#include <openssl/hmac.h>
#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/buffer.h>
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;
}
And to compile this just use the following command:
cc -o base64 base64.c -lssl


















February 8th, 2007 at 9:16 am
thanks for the code , but can you try to compile your code next time before you release it ????
February 8th, 2007 at 10:16 am
Sorry about that. I believe somewhere along the line an upgrade to the blog software converted some of the code into html. It should be good now.
February 20th, 2007 at 10:44 am
Can you Plz publish a parallel function for Base64 decoding?
February 28th, 2007 at 8:27 am
[...] Someone asked for an example of decoding with OpenSSL on the Howto base64 encode with C/C++ and OpenSSL post. So here it is: #include <string.h> [...]
September 13th, 2007 at 4:54 am
Ha, I just noticed this now after
figuring out myself how to do it:
http://www.pixelbeat.org/programming/lib_crypto.html
Referenced there is a small wrapper library
around libcrypto that uses the same
method you do for base64 encoding
(the lib also has interfaces for digests,
and symmetric and assymetric ciphers).
Note my lib is a little more generalised,
and also more robust in the case of memory exhaustion.
cheers,
Pádraig.
October 2nd, 2007 at 11:52 am
Hi.
I tested your program and it good i like.
Do you have one example to sign a document with openSSL ?
thanks.
March 19th, 2008 at 10:37 am
Hey Carson,
Thanks for the code. But do you have any idea as to why ur function base64 adds a newline ('\n') character at the end of the string.
Similarly, ut base64 decode function expects a newline character at the end.
Thanks
July 5th, 2008 at 8:19 am
Hi Subra,
base64 algorithm in itself appends a carriage return and linefeed characters after its 'linesize' character and at the end of the test to be encoded. This infact increases the length of the encoded string by about 3%, but this cannot be avoided.