Line | Branch | Exec | Source |
---|---|---|---|
1 | #include "base64.h" | ||
2 | #include "debug.h" | ||
3 | |||
4 | enum { | ||
5 | I = BASE64_INVALID, | ||
6 | P = BASE64_PADDING, | ||
7 | }; | ||
8 | |||
9 | const uint8_t base64_decode_table[256] = { | ||
10 | I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, | ||
11 | I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, | ||
12 | I, I, I, I, I, I, I, I, I, I, I, 62, I, I, I, 63, | ||
13 | 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, I, I, I, P, I, I, | ||
14 | I, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, | ||
15 | 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, I, I, I, I, I, | ||
16 | I, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, | ||
17 | 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, I, I, I, I, I, | ||
18 | I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, | ||
19 | I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, | ||
20 | I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, | ||
21 | I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, | ||
22 | I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, | ||
23 | I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, | ||
24 | I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, | ||
25 | I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I | ||
26 | }; | ||
27 | |||
28 | const char base64_encode_table[64] = { | ||
29 | "ABCDEFGHIJKLMNOPQRSTUVWXYZ" | ||
30 | "abcdefghijklmnopqrstuvwxyz" | ||
31 | "0123456789+/" | ||
32 | }; | ||
33 | |||
34 | 5 | size_t base64_encode_block(const char *in, size_t ilen, char *out, size_t olen) | |
35 | { | ||
36 | 5 | BUG_ON(ilen == 0); | |
37 | 5 | BUG_ON(ilen % 3 != 0); | |
38 | 5 | BUG_ON(ilen / 3 * 4 > olen); | |
39 | const unsigned char *u_in = in; | ||
40 | size_t o = 0; | ||
41 | |||
42 |
2/2✓ Branch 0 taken 9 times.
✓ Branch 1 taken 5 times.
|
14 | for (size_t i = 0; i < ilen; ) { |
43 | 9 | uint32_t a = u_in[i++]; | |
44 | 9 | uint32_t b = u_in[i++]; | |
45 | 9 | uint32_t c = u_in[i++]; | |
46 | 9 | uint32_t v = a << 16 | b << 8 | c; | |
47 | 9 | out[o++] = base64_encode_table[(v >> 18) & 63]; | |
48 | 9 | out[o++] = base64_encode_table[(v >> 12) & 63]; | |
49 | 9 | out[o++] = base64_encode_table[(v >> 6) & 63]; | |
50 | 9 | out[o++] = base64_encode_table[(v >> 0) & 63]; | |
51 | } | ||
52 | |||
53 | 5 | return o; | |
54 | } | ||
55 | |||
56 | 5 | void base64_encode_final(const char *in, size_t ilen, char out[4]) | |
57 | { | ||
58 | 5 | BUG_ON(ilen - 1 > 1); | |
59 | 5 | const unsigned char *u_in = in; | |
60 | 5 | uint32_t a = u_in[0]; | |
61 |
2/2✓ Branch 0 taken 3 times.
✓ Branch 1 taken 2 times.
|
5 | uint32_t b = (ilen == 2) ? u_in[1] : 0; |
62 | 5 | uint32_t v = a << 16 | b << 8; | |
63 |
2/2✓ Branch 0 taken 3 times.
✓ Branch 1 taken 2 times.
|
5 | char x = (ilen == 2) ? base64_encode_table[(v >> 6) & 63] : '='; |
64 | 5 | out[0] = base64_encode_table[(v >> 18) & 63]; | |
65 | 5 | out[1] = base64_encode_table[(v >> 12) & 63]; | |
66 | 5 | out[2] = x; | |
67 | 5 | out[3] = '='; | |
68 | 5 | } | |
69 |