4 Copyright (C) 2006-2009 Jonathan Zarate
12 111111 110000 000011 111111
15 echo -n "aaa" | uuencode -m -
19 echo -n "a" | uuencode -m -
23 echo -n "aa" | uuencode -m -
29 static const char base64_xlat
[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
32 int base64_encode(const unsigned char *in
, char *out
, int inlen
)
38 *out
++ = base64_xlat
[*in
>> 2];
39 *out
++ = base64_xlat
[((*in
<< 4) & 0x3F) | (*(in
+ 1) >> 4)];
40 ++in
; // note: gcc complains if *(++in)
41 *out
++ = base64_xlat
[((*in
<< 2) & 0x3F) | (*(in
+ 1) >> 6)];
43 *out
++ = base64_xlat
[*in
++ & 0x3F];
47 *out
++ = base64_xlat
[*in
>> 2];
49 *out
++ = base64_xlat
[((*in
<< 4) & 0x3F) | (*(in
+ 1) >> 4)];
51 *out
++ = base64_xlat
[((*in
<< 2) & 0x3F)];
54 *out
++ = base64_xlat
[(*in
<< 4) & 0x3F];
63 int base64_decode(const char *in
, unsigned char *out
, int inlen
)
75 if (*in
== '=') break;
76 if ((p
= strchr(base64_xlat
, c
= *in
++)) == NULL
) {
77 // printf("ignored - %x %c\n", c, c);
78 continue; // note: invalid characters are just ignored
80 x
= (x
<< 6) | (p
- base64_xlat
);
83 *out
++ = (x
>> 8) & 0xFF;
91 *out
++ = (x
>> 2) & 0xFF;
99 int base64_encoded_len(int len
)
101 return ((len
+ 2) / 3) * 4;
104 int base64_decoded_len(int len
)
106 return ((len
+ 3) / 4) * 3;
110 int main(int argc, char **argv)
118 memset(buf, 0, sizeof(buf));
119 base64_encode(test, buf, strlen(test));
120 printf("buf=%s\n", buf);
122 memset(buf2, 0, sizeof(buf2));
123 base64_decode(buf, buf2, base64_encoded_len(strlen(test)));
124 printf("buf2=%s\n", buf2);