2 * Copyright (C), 2000-2004 by the monit project group.
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License as
7 * published by the Free Software Foundation; either version 2 of the
8 * License, or (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 Foundation,
17 * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 /* base64 encoding/decoding
21 * Author: Jan-Henrik Haukeland <hauk@tildeslash.com>
32 static int is_base64(char c);
33 static char encode(unsigned char u);
34 static unsigned char decode(char c);
36 /* Global variables */
37 char *decode_base64(const char *src);
38 char *encode_base64(int size, char *src);
41 /* Base64 encode and return size data in 'src'. The caller must free the
43 * Returns encoded string otherwise NULL
45 char *encode_base64(int size, char *src)
55 size = strlen((char *)src);
58 out = (char *)calloc(sizeof(char), size * 4 / 3 + 4);
65 for (i = 0; i < size; i += 3) {
66 unsigned char b1 = 0, b2 = 0, b3 = 0, b4 = 0, b5 = 0, b6 = 0, b7 = 0;
79 b5 = ((b1 & 0x3) << 4) | (b2 >> 4);
80 b6 = ((b2 & 0xf) << 2) | (b3 >> 6);
102 /* Decode the base64 encoded string 'src' into the memory pointed to by
103 * 'dest'. The dest buffer is NUL terminated.
104 * Returns NULL in case of error
106 char *decode_base64(const char *src)
111 int k, l = strlen(src) + 1;
114 /* The size of the dest will always be less than the source */
115 dest = (char *)calloc(sizeof(char), l + 13);
120 p = (unsigned char *)dest;
122 buf = (unsigned char *) malloc(l);
128 /* Ignore non base64 chars as per the POSIX standard */
129 for (k = 0, l = 0; src[k]; k++) {
130 if (is_base64(src[k])) {
135 for (k = 0; k < l; k += 4) {
136 char c1 = 'A', c2 = 'A', c3 = 'A', c4 = 'A';
137 unsigned char b1 = 0, b2 = 0, b3 = 0, b4 = 0;
158 *p++ = ((b1 << 2) | (b2 >> 4) );
161 *p++ = (((b2 & 0xf) << 4) | (b3 >> 2) );
165 *p++ = (((b3 & 0x3) << 6) | b4 );
177 static char encode(unsigned char u)
183 return 'a' + (u - 26);
186 return '0' + (u - 52);
195 /* Decode a base64 character */
196 static unsigned char decode(char c)
198 if (c >= 'A' && c <= 'Z') {
201 if (c >= 'a' && c <= 'z') {
202 return (c - 'a' + 26);
204 if (c >= '0' && c <= '9') {
205 return (c - '0' + 52);
214 /* Returns TRUE if 'c' is a valid base64 character, otherwise FALSE */
215 static int is_base64(char c)
217 if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
218 (c >= '0' && c <= '9') || (c == '+') ||
219 (c == '/') || (c == '=')) {