summaryrefslogtreecommitdiffstats
path: root/friendfinder/crypto.c
blob: d97144c486ef9a27ceb21e1f111fdd1a4218c8e4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <stdio.h>
#include <string.h>

#include <openssl/pem.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/evp.h>

#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);
	memmove(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;
}