1 /* This file is part of GDBM, the GNU data base manager.
2 Copyright (C) 2011, 2013 Free Software Foundation, Inc.
4 GDBM is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 3, or (at your option)
9 GDBM is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with GDBM. If not, see <http://www.gnu.org/licenses/>. */
17 # include "autoconf.h"
18 # include "gdbmdefs.h"
21 static char b64tab[] =
22 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
23 static int b64val[128] = {
24 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
25 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
26 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
27 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
28 -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
29 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
30 -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
31 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1
35 _gdbm_base64_encode (const unsigned char *input, size_t input_len,
36 unsigned char **output, size_t *output_size,
39 size_t olen = 4 * (input_len + 2) / 3 + 1;
42 if (olen > *output_size)
44 out = realloc (*output, olen);
46 return GDBM_MALLOC_ERROR;
53 while (input_len >= 3)
55 *out++ = b64tab[input[0] >> 2];
56 *out++ = b64tab[((input[0] << 4) & 0x30) | (input[1] >> 4)];
57 *out++ = b64tab[((input[1] << 2) & 0x3c) | (input[2] >> 6)];
58 *out++ = b64tab[input[2] & 0x3f];
65 unsigned char c = (input[0] << 4) & 0x30;
66 *out++ = b64tab[input[0] >> 2];
70 *out++ = (input_len < 2) ? '=' : b64tab[(input[1] << 2) & 0x3c];
74 *nbytes = out - *output;
79 _gdbm_base64_decode (const unsigned char *input, size_t input_len,
80 unsigned char **output, size_t *output_size,
81 size_t *inbytes, size_t *outbytes)
88 if (olen > *output_size)
90 out = realloc (*output, olen);
92 return GDBM_MALLOC_ERROR;
103 if (input[0] > 127 || b64val[input[0]] == -1
104 || input[1] > 127 || b64val[input[1]] == -1
105 || input[2] > 127 || ((input[2] != '=') && (b64val[input[2]] == -1))
106 || input[3] > 127 || ((input[3] != '=')
107 && (b64val[input[3]] == -1)))
109 rc = GDBM_ILLEGAL_DATA;
112 *out++ = (b64val[input[0]] << 2) | (b64val[input[1]] >> 4);
115 *out++ = ((b64val[input[1]] << 4) & 0xf0) | (b64val[input[2]] >> 2);
117 *out++ = ((b64val[input[2]] << 6) & 0xc0) | b64val[input[3]];
123 while (input_len > 0);
125 *outbytes = out - *output;