1 /*
2 * Copyright (C) 2015 Red Hat
3 *
4 * This file is part of ocserv.
5 *
6 * ocserv is free software: you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * ocserv is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include <config.h>
21 #include <nettle/base64.h>
22 #include <talloc.h>
23 #include "base64-helper.h"
24
oc_base64_encode(const char * restrict in,size_t inlen,char * restrict out,size_t outlen)25 void oc_base64_encode (const char *restrict in, size_t inlen,
26 char *restrict out, size_t outlen)
27 {
28 unsigned raw = BASE64_ENCODE_RAW_LENGTH(inlen);
29 if (outlen < raw+1) {
30 snprintf(out, outlen, "(too long data)");
31 return;
32 }
33 base64_encode_raw((void*)out, inlen, (uint8_t*)in);
34 out[raw] = 0;
35 return;
36 }
37
38 int
oc_base64_decode(const uint8_t * src,unsigned src_length,uint8_t * dst,size_t * dst_length)39 oc_base64_decode(const uint8_t *src, unsigned src_length,
40 uint8_t *dst, size_t *dst_length)
41 {
42 struct base64_decode_ctx ctx;
43 int ret;
44
45 base64_decode_init(&ctx);
46
47 #ifdef NETTLE_OLD_BASE64_API
48 {
49 unsigned int len = *dst_length;
50 ret = base64_decode_update(&ctx, &len, dst, src_length, src);
51 if (ret != 0)
52 *dst_length = len;
53 }
54 #else
55 ret = base64_decode_update(&ctx, dst_length, dst, src_length, (void*)src);
56 #endif
57
58 if (ret == 0)
59 return 0;
60
61 return base64_decode_final(&ctx);
62 }
63
oc_base64_decode_alloc(void * pool,const char * in,size_t inlen,char ** out,size_t * outlen)64 int oc_base64_decode_alloc(void *pool, const char *in, size_t inlen,
65 char **out, size_t *outlen)
66 {
67 int len, ret;
68 void *tmp;
69
70 len = BASE64_DECODE_LENGTH(inlen);
71
72 tmp = talloc_size(pool, len);
73 if (tmp == NULL)
74 return 0;
75
76 *outlen = len;
77 ret = oc_base64_decode((void*)in, inlen, tmp, outlen);
78 if (ret == 0) {
79 talloc_free(tmp);
80 return 0;
81 }
82
83 *out = tmp;
84
85 return 1;
86 }
87