Add PPTP runtime and GUI
[tomato.git] / release / src / router / shared / base64.c
blobe3b165eac19c63297b1ae5ec192291dda3c27ea9
1 /*
3 Tomato Firmware
4 Copyright (C) 2006-2009 Jonathan Zarate
6 */
7 #include <stdio.h>
8 #include <string.h>
12 111111 110000 000011 111111
13 0 1 2
15 echo -n "aaa" | uuencode -m -
16 begin-base64 644 -
17 YWFh
19 echo -n "a" | uuencode -m -
20 begin-base64 644 -
21 YQ==
23 echo -n "aa" | uuencode -m -
24 begin-base64 644 -
25 YWE=
29 static const char base64_xlat[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
32 int base64_encode(const unsigned char *in, char *out, int inlen)
34 char *o;
36 o = out;
37 while (inlen >= 3) {
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)];
42 ++in;
43 *out++ = base64_xlat[*in++ & 0x3F];
44 inlen -= 3;
46 if (inlen > 0) {
47 *out++ = base64_xlat[*in >> 2];
48 if (inlen == 2) {
49 *out++ = base64_xlat[((*in << 4) & 0x3F) | (*(in + 1) >> 4)];
50 ++in;
51 *out++ = base64_xlat[((*in << 2) & 0x3F)];
53 else {
54 *out++ = base64_xlat[(*in << 4) & 0x3F];
55 *out++ = '=';
57 *out++ = '=';
59 return out - o;
63 int base64_decode(const char *in, unsigned char *out, int inlen)
65 char *p;
66 int n;
67 unsigned long x;
68 unsigned char *o;
69 char c;
71 o = out;
72 n = 0;
73 x = 0;
74 while (inlen-- > 0) {
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);
81 if (++n == 4) {
82 *out++ = x >> 16;
83 *out++ = (x >> 8) & 0xFF;
84 *out++ = x & 0xFF;
85 n = 0;
86 x = 0;
89 if (n == 3) {
90 *out++ = x >> 10;
91 *out++ = (x >> 2) & 0xFF;
93 else if (n == 2) {
94 *out++ = x >> 4;
96 return out - o;
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)
112 char *test = "a";
113 char buf[128];
114 char buf2[128];
115 const char *in;
116 int len;
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);