| 1 |
#include "base64.h" |
| 2 |
#include "../otfcc-alloc.h" |
| 3 |
|
| 4 |
static const uint8_t base64_table[64] = |
| 5 |
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; |
| 6 |
|
| 7 |
uint8_t *base64_encode(const uint8_t *src, size_t len, size_t *out_len) { |
| 8 |
uint8_t *out, *pos; |
| 9 |
const uint8_t *end, *in; |
| 10 |
size_t olen; |
| 11 |
|
| 12 |
olen = (len + 3 - 1) / 3 * 4; /* 3-byte blocks to 4-byte */ |
| 13 |
olen++; /* nul termination */ |
| 14 |
out = __caryll_malloc(sizeof(uint8_t) * olen); |
| 15 |
if (out == NULL) return NULL; |
| 16 |
|
| 17 |
end = src + len; |
| 18 |
in = src; |
| 19 |
pos = out; |
| 20 |
while (end - in >= 3) { |
| 21 |
*pos++ = base64_table[in[0] >> 2]; |
| 22 |
*pos++ = base64_table[((in[0] & 0x03) << 4) | (in[1] >> 4)]; |
| 23 |
*pos++ = base64_table[((in[1] & 0x0f) << 2) | (in[2] >> 6)]; |
| 24 |
*pos++ = base64_table[in[2] & 0x3f]; |
| 25 |
in += 3; |
| 26 |
} |
| 27 |
|
| 28 |
if (end - in) { |
| 29 |
*pos++ = base64_table[in[0] >> 2]; |
| 30 |
if (end - in == 1) { |
| 31 |
*pos++ = base64_table[(in[0] & 0x03) << 4]; |
| 32 |
*pos++ = '='; |
| 33 |
} else { |
| 34 |
*pos++ = base64_table[((in[0] & 0x03) << 4) | (in[1] >> 4)]; |
| 35 |
*pos++ = base64_table[(in[1] & 0x0f) << 2]; |
| 36 |
} |
| 37 |
*pos++ = '='; |
| 38 |
} |
| 39 |
|
| 40 |
*pos = '\0'; |
| 41 |
if (out_len) *out_len = pos - out; |
| 42 |
return out; |
| 43 |
} |
| 44 |
|
| 45 |
uint8_t *base64_decode(const uint8_t *src, size_t len, size_t *out_len) { |
| 46 |
uint8_t dtable[256], *out, *pos, in[4], block[4], tmp; |
| 47 |
size_t i, count; |
| 48 |
|
| 49 |
memset(dtable, 0x80, 256); |
| 50 |
for (i = 0; i < sizeof(base64_table); i++) |
| 51 |
dtable[base64_table[i]] = i; |
| 52 |
dtable['='] = 0; |
| 53 |
|
| 54 |
count = 0; |
| 55 |
for (i = 0; i < len; i++) { |
| 56 |
if (dtable[src[i]] != 0x80) count++; |
| 57 |
} |
| 58 |
|
| 59 |
if (count % 4) return NULL; |
| 60 |
|
| 61 |
pos = out = __caryll_malloc(sizeof(uint8_t) * count); |
| 62 |
if (out == NULL) return NULL; |
| 63 |
|
| 64 |
count = 0; |
| 65 |
for (i = 0; i < len; i++) { |
| 66 |
tmp = dtable[src[i]]; |
| 67 |
if (tmp == 0x80) continue; |
| 68 |
|
| 69 |
in[count] = src[i]; |
| 70 |
block[count] = tmp; |
| 71 |
count++; |
| 72 |
if (count == 4) { |
| 73 |
*pos++ = (block[0] << 2) | (block[1] >> 4); |
| 74 |
*pos++ = (block[1] << 4) | (block[2] >> 2); |
| 75 |
*pos++ = (block[2] << 6) | block[3]; |
| 76 |
count = 0; |
| 77 |
} |
| 78 |
} |
| 79 |
|
| 80 |
if (pos > out) { |
| 81 |
if (in[2] == '=') |
| 82 |
pos -= 2; |
| 83 |
else if (in[3] == '=') |
| 84 |
pos--; |
| 85 |
} |
| 86 |
|
| 87 |
*out_len = pos - out; |
| 88 |
return out; |
| 89 |
} |