2 * Base64 encoding/decoding (RFC1341)
3 * Copyright (c) 2005-2011, Jouni Malinen <j@w1.fi>
5 * This software may be distributed under the terms of the BSD license.
6 * See README for more details.
14 static const unsigned char base64_table[65] =
15 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
18 * base64_encode - Base64 encode
19 * @src: Data to be encoded
20 * @len: Length of the data to be encoded
21 * @out_len: Pointer to output length variable, or %NULL if not used
22 * Returns: Allocated buffer of out_len bytes of encoded data,
25 * Caller is responsible for freeing the returned buffer. Returned buffer is
26 * nul terminated to make it easier to use as a C string. The nul terminator is
27 * not included in out_len.
29 unsigned char * base64_encode(const unsigned char *src, size_t len,
32 unsigned char *out, *pos;
33 const unsigned char *end, *in;
37 olen = len * 4 / 3 + 4; /* 3-byte blocks to 4-byte */
38 olen += olen / 72; /* line feeds */
39 olen++; /* nul termination */
41 return NULL; /* integer overflow */
42 out = os_malloc(olen);
50 while (end - in >= 3) {
51 *pos++ = base64_table[in[0] >> 2];
52 *pos++ = base64_table[((in[0] & 0x03) << 4) | (in[1] >> 4)];
53 *pos++ = base64_table[((in[1] & 0x0f) << 2) | (in[2] >> 6)];
54 *pos++ = base64_table[in[2] & 0x3f];
64 *pos++ = base64_table[in[0] >> 2];
66 *pos++ = base64_table[(in[0] & 0x03) << 4];
69 *pos++ = base64_table[((in[0] & 0x03) << 4) |
71 *pos++ = base64_table[(in[1] & 0x0f) << 2];
88 * base64_decode - Base64 decode
89 * @src: Data to be decoded
90 * @len: Length of the data to be decoded
91 * @out_len: Pointer to output length variable
92 * Returns: Allocated buffer of out_len bytes of decoded data,
95 * Caller is responsible for freeing the returned buffer.
97 unsigned char * base64_decode(const unsigned char *src, size_t len,
100 unsigned char dtable[256], *out, *pos, block[4], tmp;
101 size_t i, count, olen;
104 os_memset(dtable, 0x80, 256);
105 for (i = 0; i < sizeof(base64_table) - 1; i++)
106 dtable[base64_table[i]] = (unsigned char) i;
110 for (i = 0; i < len; i++) {
111 if (dtable[src[i]] != 0x80)
115 if (count == 0 || count % 4)
118 olen = count / 4 * 3;
119 pos = out = os_malloc(olen);
124 for (i = 0; i < len; i++) {
125 tmp = dtable[src[i]];
134 *pos++ = (block[0] << 2) | (block[1] >> 4);
135 *pos++ = (block[1] << 4) | (block[2] >> 2);
136 *pos++ = (block[2] << 6) | block[3];
144 /* Invalid padding */
153 *out_len = pos - out;