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 if_assert_failed
return NULL
;
23 return base64_encode_bin(in
, strlen(in
), NULL
);
27 base64_encode_bin(register unsigned char *in
, int inlen
, int *outlen
)
30 unsigned char *outstr
;
33 if_assert_failed
return NULL
;
35 out
= outstr
= mem_alloc((inlen
/ 3) * 4 + 4 + 1);
36 if (!out
) return NULL
;
39 *out
++ = base64_chars
[ *in
>> 2 ];
40 *out
++ = base64_chars
[ (*in
<< 4 | *(in
+ 1) >> 4) & 63 ];
41 *out
++ = base64_chars
[ (*(in
+ 1) << 2 | *(in
+ 2) >> 6) & 63 ];
42 *out
++ = base64_chars
[ *(in
+ 2) & 63 ];
46 *out
++ = base64_chars
[ *in
>> 2 ];
47 *out
++ = base64_chars
[ *in
<< 4 & 63 ];
52 *out
++ = base64_chars
[ *in
>> 2 ];
53 *out
++ = base64_chars
[ (*in
<< 4 | *(in
+ 1) >> 4) & 63 ];
54 *out
++ = base64_chars
[ (*(in
+ 1) << 2) & 63 ];
65 /* Base64 decoding is used only with the CONFIG_FORMHIST or CONFIG_GSSAPI
66 feature, so i'll #ifdef it */
67 #if defined(CONFIG_FORMHIST) || defined(CONFIG_GSSAPI)
70 base64_decode(register unsigned char *in
)
73 if_assert_failed
return NULL
;
75 return base64_decode_bin(in
, strlen(in
), NULL
);
78 /* base64_decode: @in string to decode
79 * returns the string decoded (must be freed by the caller) */
81 base64_decode_bin(register unsigned char *in
, int inlen
, int *outlen
)
83 static unsigned char is_base64_char
[256]; /* static to force initialization at zero */
84 static unsigned char decode
[256];
86 unsigned char *outstr
;
88 unsigned int bits
= 0;
92 if_assert_failed
return NULL
;
94 outstr
= out
= mem_alloc(inlen
/ 4 * 3 + 1);
95 if (!outstr
) return NULL
;
98 int i
= sizeof(base64_chars
) - 1;
101 is_base64_char
[base64_chars
[i
]] = 1;
102 decode
[base64_chars
[i
]] = i
;
109 if (*in
== '=') break;
110 if (!is_base64_char
[*in
])
117 *out
++ = (bits
>> 8) & 0xff;
118 *out
++ = bits
& 0xff;
129 if (count
) goto decode_error
;
140 *out
++ = (bits
>> 8) & 0xff;
148 *outlen
= out
-outstr
;
157 #endif /* CONFIG_FORMHIST */