summaryrefslogtreecommitdiffstats
path: root/PICA_id.c
blob: f30d03f482fa7d01fbf5c5a512800c2de2adbaaa (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
/*
	(c) Copyright  2012 - 2018 Anton Sviridenko
	https://picapica.im

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, version 3.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

#include "PICA_id.h"
#include <openssl/bio.h>
#include <string.h>

int PICA_id_from_X509(X509 *x, unsigned char *id)
{
	unsigned char *der = NULL;
	int len;

	len = i2d_X509(x, &der);

	if (len <= 0)
	{
		return 0;
	}

	SHA224(der, len, id);

	OPENSSL_free(der);

	return 1;
}

unsigned char *PICA_id_from_base64(const unsigned char *buf, unsigned char *id)
{
	BIO *biomem, *b64;
	static char localidbuf[PICA_ID_SIZE];
	int inlen, bread = 0;
	unsigned char *idbuf = id;

	b64 = BIO_new(BIO_f_base64());
	BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
	biomem = BIO_new_mem_buf(buf, -1);
	biomem = BIO_push(b64, biomem);

	if (idbuf == NULL)
		idbuf = localidbuf;

	bread = BIO_read(biomem, idbuf, PICA_ID_SIZE);

	if (bread != PICA_ID_SIZE)
		idbuf = NULL;

	BIO_free_all(biomem);

	return idbuf;
}

char *PICA_id_to_base64(const unsigned char *id, char *buf)
{
	BIO *biomem, *b64;
	static char localbuf[PICA_ID_SIZE * 2];

	char *sourcebuf, *outputbuf = buf;
	char *newlinepos;
	long b64len;

	b64 = BIO_new(BIO_f_base64());
	biomem = BIO_new(BIO_s_mem());
	biomem = BIO_push(b64, biomem);
	BIO_write(biomem, id, PICA_ID_SIZE);
	BIO_flush(biomem);

	b64len = BIO_get_mem_data(biomem, &sourcebuf);

	if (outputbuf == NULL)
		outputbuf = localbuf;

	memcpy(outputbuf, sourcebuf, b64len);

	outputbuf[b64len] = '\0';
	if ((newlinepos = strchr(outputbuf, '\n')))
		*newlinepos = '\0';

	BIO_free_all(biomem);

	return outputbuf;
}