1 /* Base64 encode/decode implementation. */
11 #include "util/base64.h"
12 #include "util/error.h"
13 #include "util/memory.h"
15 static unsigned char base64_chars
[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
18 base64_encode(register unsigned char *in
)
21 unsigned char *outstr
;
25 if_assert_failed
return NULL
;
28 out
= outstr
= mem_alloc((inlen
/ 3) * 4 + 4 + 1);
29 if (!out
) return NULL
;
32 *out
++ = base64_chars
[ *in
>> 2 ];
33 *out
++ = base64_chars
[ (*in
<< 4 | *(in
+ 1) >> 4) & 63 ];
34 *out
++ = base64_chars
[ (*(in
+ 1) << 2 | *(in
+ 2) >> 6) & 63 ];
35 *out
++ = base64_chars
[ *(in
+ 2) & 63 ];
39 *out
++ = base64_chars
[ *in
>> 2 ];
40 *out
++ = base64_chars
[ *in
<< 4 & 63 ];
45 *out
++ = base64_chars
[ *in
>> 2 ];
46 *out
++ = base64_chars
[ (*in
<< 4 | *(in
+ 1) >> 4) & 63 ];
47 *out
++ = base64_chars
[ (*(in
+ 1) << 2) & 63 ];
55 /* Base64 decoding is used only with the CONFIG_FORMHIST feature, so i'll #ifdef it */
56 #ifdef CONFIG_FORMHIST
58 /* base64_decode: @in string to decode
59 * returns the string decoded (must be freed by the caller) */
61 base64_decode(register unsigned char *in
)
63 static unsigned char is_base64_char
[256]; /* static to force initialization at zero */
64 static unsigned char decode
[256];
66 unsigned char *outstr
;
68 unsigned int bits
= 0;
72 if_assert_failed
return NULL
;
74 outstr
= out
= mem_alloc(strlen(in
) / 4 * 3 + 1);
75 if (!outstr
) return NULL
;
78 int i
= sizeof(base64_chars
) - 1;
81 is_base64_char
[base64_chars
[i
]] = 1;
82 decode
[base64_chars
[i
]] = i
;
89 if (*in
== '=') break;
90 if (!is_base64_char
[*in
])
97 *out
++ = (bits
>> 8) & 0xff;
109 if (count
) goto decode_error
;
120 *out
++ = (bits
>> 8) & 0xff;
133 #endif /* CONFIG_FORMHIST */