2
* Base64 encoding/decoding (RFC1341)
3
* Copyright (c) 2005, Jouni Malinen <j@w1.fi>
5
* This program is free software; you can redistribute it and/or modify
6
* it under the terms of the GNU General Public License version 2 as
7
* published by the Free Software Foundation.
9
* Alternatively, this software may be distributed under the terms of BSD
12
* See README and COPYING for more details.
20
static const unsigned char base64_table[65] =
21
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
24
* base64_encode - Base64 encode
25
* @src: Data to be encoded
26
* @len: Length of the data to be encoded
27
* @out_len: Pointer to output length variable, or %NULL if not used
28
* Returns: Allocated buffer of out_len bytes of encoded data,
31
* Caller is responsible for freeing the returned buffer. Returned buffer is
32
* nul terminated to make it easier to use as a C string. The nul terminator is
33
* not included in out_len.
35
unsigned char * base64_encode(const unsigned char *src, size_t len,
38
unsigned char *out, *pos;
39
const unsigned char *end, *in;
43
olen = len * 4 / 3 + 4; /* 3-byte blocks to 4-byte */
44
olen += olen / 72; /* line feeds */
45
olen++; /* nul termination */
47
return NULL; /* integer overflow */
48
out = os_malloc(olen);
56
while (end - in >= 3) {
57
*pos++ = base64_table[in[0] >> 2];
58
*pos++ = base64_table[((in[0] & 0x03) << 4) | (in[1] >> 4)];
59
*pos++ = base64_table[((in[1] & 0x0f) << 2) | (in[2] >> 6)];
60
*pos++ = base64_table[in[2] & 0x3f];
70
*pos++ = base64_table[in[0] >> 2];
72
*pos++ = base64_table[(in[0] & 0x03) << 4];
75
*pos++ = base64_table[((in[0] & 0x03) << 4) |
77
*pos++ = base64_table[(in[1] & 0x0f) << 2];
94
* base64_decode - Base64 decode
95
* @src: Data to be decoded
96
* @len: Length of the data to be decoded
97
* @out_len: Pointer to output length variable
98
* Returns: Allocated buffer of out_len bytes of decoded data,
101
* Caller is responsible for freeing the returned buffer.
103
unsigned char * base64_decode(const unsigned char *src, size_t len,
106
unsigned char dtable[256], *out, *pos, in[4], block[4], tmp;
107
size_t i, count, olen;
109
os_memset(dtable, 0x80, 256);
110
for (i = 0; i < sizeof(base64_table) - 1; i++)
111
dtable[base64_table[i]] = (unsigned char) i;
115
for (i = 0; i < len; i++) {
116
if (dtable[src[i]] != 0x80)
120
if (count == 0 || count % 4)
123
olen = count / 4 * 3;
124
pos = out = os_malloc(olen);
129
for (i = 0; i < len; i++) {
130
tmp = dtable[src[i]];
138
*pos++ = (block[0] << 2) | (block[1] >> 4);
139
*pos++ = (block[1] << 4) | (block[2] >> 2);
140
*pos++ = (block[2] << 6) | block[3];
148
else if (in[3] == '=')
152
*out_len = pos - out;