diff options
Diffstat (limited to 'lib/base64.c')
-rw-r--r-- | lib/base64.c | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/lib/base64.c b/lib/base64.c new file mode 100644 index 0000000..1f1fcb8 --- /dev/null +++ b/lib/base64.c | |||
@@ -0,0 +1,50 @@ | |||
1 | /**************************************************************************** | ||
2 | * Function to encode in Base64 | ||
3 | * | ||
4 | * Written by Lauri Alanko | ||
5 | * | ||
6 | *****************************************************************************/ | ||
7 | |||
8 | #include "common.h" | ||
9 | #include "base64.h" | ||
10 | |||
11 | char * | ||
12 | base64 (const char *bin, size_t len) | ||
13 | { | ||
14 | |||
15 | char *buf = (char *) malloc ((len + 2) / 3 * 4 + 1); | ||
16 | size_t i = 0, j = 0; | ||
17 | |||
18 | char BASE64_END = '='; | ||
19 | char base64_table[64]; | ||
20 | strncpy (base64_table, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", 64); | ||
21 | |||
22 | while (j < len - 2) { | ||
23 | buf[i++] = base64_table[bin[j] >> 2]; | ||
24 | buf[i++] = base64_table[((bin[j] & 3) << 4) | (bin[j + 1] >> 4)]; | ||
25 | buf[i++] = base64_table[((bin[j + 1] & 15) << 2) | (bin[j + 2] >> 6)]; | ||
26 | buf[i++] = base64_table[bin[j + 2] & 63]; | ||
27 | j += 3; | ||
28 | } | ||
29 | |||
30 | switch (len - j) { | ||
31 | case 1: | ||
32 | buf[i++] = base64_table[bin[j] >> 2]; | ||
33 | buf[i++] = base64_table[(bin[j] & 3) << 4]; | ||
34 | buf[i++] = BASE64_END; | ||
35 | buf[i++] = BASE64_END; | ||
36 | break; | ||
37 | case 2: | ||
38 | buf[i++] = base64_table[bin[j] >> 2]; | ||
39 | buf[i++] = base64_table[((bin[j] & 3) << 4) | (bin[j + 1] >> 4)]; | ||
40 | buf[i++] = base64_table[(bin[j + 1] & 15) << 2]; | ||
41 | buf[i++] = BASE64_END; | ||
42 | break; | ||
43 | case 0: | ||
44 | break; | ||
45 | } | ||
46 | |||
47 | buf[i] = '\0'; | ||
48 | return buf; | ||
49 | } | ||
50 | |||