1 /** Base64 encode/decode implementation.
12 #include "util/base64.h"
13 #include "util/error.h"
14 #include "util/memory.h"
16 static unsigned char base64_chars
[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
19 base64_encode(register unsigned char *in
)
22 if_assert_failed
return NULL
;
24 return base64_encode_bin(in
, strlen(in
), NULL
);
28 base64_encode_bin(register unsigned char *in
, int inlen
, int *outlen
)
31 unsigned char *outstr
;
34 if_assert_failed
return NULL
;
36 out
= outstr
= mem_alloc((inlen
/ 3) * 4 + 4 + 1);
37 if (!out
) return NULL
;
40 *out
++ = base64_chars
[ *in
>> 2 ];
41 *out
++ = base64_chars
[ (*in
<< 4 | *(in
+ 1) >> 4) & 63 ];
42 *out
++ = base64_chars
[ (*(in
+ 1) << 2 | *(in
+ 2) >> 6) & 63 ];
43 *out
++ = base64_chars
[ *(in
+ 2) & 63 ];
47 *out
++ = base64_chars
[ *in
>> 2 ];
48 *out
++ = base64_chars
[ *in
<< 4 & 63 ];
53 *out
++ = base64_chars
[ *in
>> 2 ];
54 *out
++ = base64_chars
[ (*in
<< 4 | *(in
+ 1) >> 4) & 63 ];
55 *out
++ = base64_chars
[ (*(in
+ 1) << 2) & 63 ];
66 /* Base64 decoding is used only with the CONFIG_FORMHIST or CONFIG_GSSAPI
67 feature, so i'll #ifdef it */
68 #if defined(CONFIG_FORMHIST) || defined(CONFIG_GSSAPI)
71 base64_decode(register unsigned char *in
)
74 if_assert_failed
return NULL
;
76 return base64_decode_bin(in
, strlen(in
), NULL
);
79 /** Decode a Base64 string.
80 * @param in Input Base64 string
81 * @param inlen Length of @a in, in bytes
82 * @param[out] outlen Length of decoded string
84 * @returns the string decoded (must be freed by the caller)
85 * or NULL if an error occurred (syntax error or out of memory) */
87 base64_decode_bin(register unsigned char *in
, int inlen
, int *outlen
)
89 static unsigned char is_base64_char
[256]; /* static to force initialization at zero */
90 static unsigned char decode
[256];
92 unsigned char *outstr
;
94 unsigned int bits
= 0;
98 if_assert_failed
return NULL
;
100 outstr
= out
= mem_alloc(inlen
/ 4 * 3 + 1);
101 if (!outstr
) return NULL
;
104 int i
= sizeof(base64_chars
) - 1;
107 is_base64_char
[base64_chars
[i
]] = 1;
108 decode
[base64_chars
[i
]] = i
;
115 if (*in
== '=') break;
116 if (!is_base64_char
[*in
])
123 *out
++ = (bits
>> 8) & 0xff;
124 *out
++ = bits
& 0xff;
135 if (count
) goto decode_error
;
146 *out
++ = (bits
>> 8) & 0xff;
154 *outlen
= out
-outstr
;
163 #endif /* CONFIG_FORMHIST */