#include #include #include #include #include #include #include "cryptossl.h" #define dump_sslerror() \ do {\ unsigned long err = ERR_get_error(); \ ERR_load_crypto_strings(); \ printf("%s:%i %s\n", __FILE__, __LINE__, ERR_error_string(err, NULL)); \ } while(0) #define MAX_PEM_SIZE 4096 static char buff[4096]; //XXX: stat() to get filesize! BIO* load_pem(char *filename) { FILE *file; int size; BIO *bio; file = fopen(filename, "r"); if(file == NULL) return NULL; for(size = 0; fread(buff + size, 1, 1, file) == 1; size++) { if(size >= MAX_PEM_SIZE) { fclose(file); return NULL; } } fclose(file); bio = BIO_new_mem_buf(buff, size); if(bio == NULL) dump_sslerror(); return bio; } int from_base64(char *in, int inlen, char *out, int maxlen) { BIO *b64, *bmem; memset(out, 0, maxlen); b64 = BIO_new(BIO_f_base64()); if(!strchr(in, '\n')) BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); bmem = BIO_new_mem_buf(in, inlen); bmem = BIO_push(b64, bmem); int j = BIO_ctrl_pending(bmem); int ret = BIO_read(bmem, out, j); BIO_free_all(bmem); return ret; } int to_base64(char *in, int inlen, char *out, int maxlen) { BIO *bmem, *b64; BUF_MEM *bptr; int ret; b64 = BIO_new(BIO_f_base64()); bmem = BIO_new(BIO_s_mem()); b64 = BIO_push(b64, bmem); BIO_write(b64, in, inlen); BIO_flush(b64); BIO_get_mem_ptr(b64, &bptr); if(bptr->length > maxlen) { BIO_free_all(b64); return -1; } memcpy(out, bptr->data, bptr->length-1); // XXX: we don't teminate b64 buffer as string // XXX: user gets length so wtf ;) // out[bptr->length-1] = 0; ret = bptr->length; BIO_free_all(b64); return ret; }