summaryrefslogtreecommitdiff
path: root/src/server/base64.c
blob: 7e52eb993b38b662161b4e1f623f6010bec8927d (plain)
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
#include <stddef.h>

static const char b64[] =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "abcdefghijklmnopqrstuvwxyz"
    "0123456789+/";

void base64_encode(
  const unsigned char *in,
  size_t len,
  char *out
) {
  size_t i, j = 0;

  for (i = 0; i < len; i += 3) {
    unsigned v = in[i] << 16;

    if (i + 1 < len) v |= in[i + 1] << 8;
    if (i + 2 < len) v |= in[i + 2];

    out[j++] = b64[(v >> 18) & 63];
    out[j++] = b64[(v >> 12) & 63];

    out[j++] = (i + 1 < len) ? b64[(v >> 6) & 63] : '=';
    out[j++] = (i + 2 < len) ? b64[v & 63] : '=';
  }

  out[j] = 0;
}