-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbase64.c
More file actions
89 lines (71 loc) · 1.73 KB
/
Copy pathbase64.c
File metadata and controls
89 lines (71 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <event.h>
#include "base64.h"
static const char base64_chars[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static unsigned char base64_map(const char **strp)
{
const char *str = *strp;
const char *ptr;
while (*(str = *strp) && *str != '=') {
*strp = str + 1;
ptr = strchr(base64_chars, *str);
if (ptr)
return ptr - base64_chars;
}
return 0;
}
/*
* Returns actual size of decoded buffer.
*/
size_t base64_decode(const char *str, unsigned char *buf, size_t size)
{
unsigned int n;
size_t i, j, actual = 0;
for (i = 0; *str && *str != '='; ) {
n = base64_map(&str) << 18;
n += base64_map(&str) << 12;
n += base64_map(&str) << 6;
n += base64_map(&str);
if (i < size)
buf[i++] = (n >> 16) & 255;
if (i < size)
buf[i++] = (n >> 8) & 255;
if (i < size)
buf[i++] = n & 255;
actual += 3;
}
/* account for padding */
for (j = 0; j < 3 && str[j] == '='; j ++)
actual --;
return actual;
}
int base64_encode_evbuf(struct evbuffer *evbuf, const unsigned char *s,
size_t length)
{
unsigned int n;
char string[4];
size_t i;
int ret = 0;
for (i = 0; i < length;) {
n = s[i++] << 16;
n += (i < length) ? s[i++] << 8 : 0;
n += (i < length) ? s[i++] : 0;
string[0] = base64_chars[(n >> 18) & 63];
string[1] = base64_chars[(n >> 12) & 63];
string[2] = base64_chars[(n >> 6) & 63];
string[3] = base64_chars[n & 63];
ret = evbuffer_add(evbuf, string, 4);
if (ret)
return ret;
}
/* padd to make length a multiple of 3 */
for (i = 0; length % 3 != 0; i ++, length ++)
string[i] = '=';
if (i)
ret = evbuffer_add(evbuf, string, i);
return ret;
}