xref: /openbsd-src/usr.sbin/acme-client/base64.c (revision 34335c1147cdc2ad92d0a665b641927bd5f283c0)
1*34335c11Sjsing /*	$Id: base64.c,v 1.9 2017/01/24 13:32:55 jsing Exp $ */
2de579d12Sflorian /*
3de579d12Sflorian  * Copyright (c) 2016 Kristaps Dzonsons <kristaps@bsd.lv>
4de579d12Sflorian  *
5de579d12Sflorian  * Permission to use, copy, modify, and distribute this software for any
6de579d12Sflorian  * purpose with or without fee is hereby granted, provided that the above
7de579d12Sflorian  * copyright notice and this permission notice appear in all copies.
8de579d12Sflorian  *
9de579d12Sflorian  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
10de579d12Sflorian  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11de579d12Sflorian  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
12de579d12Sflorian  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13de579d12Sflorian  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14de579d12Sflorian  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15de579d12Sflorian  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16de579d12Sflorian  */
1799418fdeSbenno 
188fddb040Stb #include <netinet/in.h>
198fddb040Stb #include <resolv.h>
20de579d12Sflorian 
21de579d12Sflorian #include <stdlib.h>
22de579d12Sflorian 
23de579d12Sflorian #include "extern.h"
24de579d12Sflorian 
25de579d12Sflorian /*
26de579d12Sflorian  * Compute the maximum buffer required for a base64 encoded string of
27de579d12Sflorian  * length "len".
28de579d12Sflorian  */
29de579d12Sflorian size_t
base64len(size_t len)30de579d12Sflorian base64len(size_t len)
31de579d12Sflorian {
32de579d12Sflorian 
33cea463a1Stb 	return (len + 2) / 3 * 4 + 1;
34de579d12Sflorian }
35de579d12Sflorian 
36de579d12Sflorian /*
37de579d12Sflorian  * Pass a stream of bytes to be base64 encoded, then converted into
38de579d12Sflorian  * base64url format.
39de579d12Sflorian  * Returns NULL on allocation failure (not logged).
40de579d12Sflorian  */
41de579d12Sflorian char *
base64buf_url(const char * data,size_t len)42de579d12Sflorian base64buf_url(const char *data, size_t len)
43de579d12Sflorian {
44de579d12Sflorian 	size_t	 i, sz;
45de579d12Sflorian 	char	*buf;
46de579d12Sflorian 
47de579d12Sflorian 	sz = base64len(len);
487cd8f039Sjsing 	if ((buf = malloc(sz)) == NULL)
49*34335c11Sjsing 		return NULL;
50de579d12Sflorian 
518fddb040Stb 	b64_ntop(data, len, buf, sz);
52de579d12Sflorian 
53de579d12Sflorian 	for (i = 0; i < sz; i++)
54cd15ff9aStedu 		switch (buf[i]) {
55cd15ff9aStedu 		case '+':
56de579d12Sflorian 			buf[i] = '-';
57cd15ff9aStedu 			break;
58cd15ff9aStedu 		case '/':
59de579d12Sflorian 			buf[i] = '_';
60cd15ff9aStedu 			break;
61cd15ff9aStedu 		case '=':
62de579d12Sflorian 			buf[i] = '\0';
63cd15ff9aStedu 			break;
64cd15ff9aStedu 		}
65de579d12Sflorian 
66cea463a1Stb 	return buf;
67de579d12Sflorian }
68