2 * This file is part of DisOrder
3 * Copyright (C) 2005, 2007 Richard Kettlewell
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
20 /** @file lib/base64.c
21 * @brief Support for MIME base64
35 static const char mime_base64_table
[] =
36 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
38 /** @brief Convert MIME base64
39 * @param s base64 data
40 * @return Decoded data
42 char *mime_base64(const char *s
, size_t *nsp
) {
49 while((c
= (unsigned char)*s
++)) {
50 if((t
= strchr(mime_base64_table
, c
))) {
51 b
[n
++] = t
- mime_base64_table
;
53 dynstr_append(&d
, (b
[0] << 2) + (b
[1] >> 4));
54 dynstr_append(&d
, (b
[1] << 4) + (b
[2] >> 2));
55 dynstr_append(&d
, (b
[2] << 6) + b
[3]);
60 dynstr_append(&d
, (b
[0] << 2) + (b
[1] >> 4));
62 dynstr_append(&d
, (b
[1] << 4) + (b
[2] >> 2));
73 /** @brief Convert a binary string to base64
74 * @param s Bytes to convert
75 * @param ns Number of bytes to convert
76 * @return Encoded data
78 * This function does not attempt to split up lines.
80 char *mime_to_base64(const uint8_t *s
, size_t ns
) {
85 /* Input bytes with output bits: AAAAAABB BBBBCCCC CCDDDDDD */
86 /* Output bytes with input bits: 000000 001111 111122 222222 */
87 dynstr_append(d
, mime_base64_table
[s
[0] >> 2]);
88 dynstr_append(d
, mime_base64_table
[((s
[0] & 3) << 4)
90 dynstr_append(d
, mime_base64_table
[((s
[1] & 15) << 2)
92 dynstr_append(d
, mime_base64_table
[s
[2] & 63]);
97 dynstr_append(d
, mime_base64_table
[s
[0] >> 2]);
100 dynstr_append(d
, mime_base64_table
[(s
[0] & 3) << 4]);
101 dynstr_append(d
, '=');
102 dynstr_append(d
, '=');
105 dynstr_append(d
, mime_base64_table
[((s
[0] & 3) << 4)
107 dynstr_append(d
, mime_base64_table
[(s
[1] & 15) << 2]);
108 dynstr_append(d
, '=');