summaryrefslogtreecommitdiff
path: root/base64.c
blob: fbce145346707386cf32a88b5004315635a9b850 (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
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
89
90
#include "base64.h"
#include "stralloc.h"
#include "substdio.h"
#include "str.h"

static char *b64alpha =
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
#define B64PAD '='

/* returns 0 ok, 1 illegal, -1 problem */

int b64decode(in,l,out)
const unsigned char *in;
int l;
stralloc *out; /* not null terminated */
{
  int i, j;
  unsigned char a[4];
  unsigned char b[3];
  char *s;

  if (l == 0)
  {
    if (!stralloc_copys(out,"")) return -1;
    return 0;
  }

  if (!stralloc_ready(out,l + 2)) return -1; /* XXX generous */
  s = out->s;

  for (i = 0;i < l;i += 4) {
    for (j = 0;j < 4;j++)
      if ((i + j) < l && in[i + j] != B64PAD)
      {
        a[j] = str_chr(b64alpha,in[i + j]);
        if (a[j] > 63) return 1;
      }
      else a[j] = 0;

    b[0] = (a[0] << 2) | (a[1] >> 4);
    b[1] = (a[1] << 4) | (a[2] >> 2);
    b[2] = (a[2] << 6) | (a[3]);

    *s++ = b[0];

    if (in[i + 1] == B64PAD) break;
    *s++ = b[1];

    if (in[i + 2] == B64PAD) break;
    *s++ = b[2];
  }
  out->len = s - out->s;
  while (out->len && !out->s[out->len - 1]) --out->len; /* XXX avoid? */
  return 0;
}

int b64encode(in,out)
stralloc *in;
stralloc *out; /* not null terminated */
{
  unsigned char a, b, c;
  int i;
  char *s;

  if (in->len == 0)
  {
    if (!stralloc_copys(out,"")) return -1;
    return 0;
  }

  if (!stralloc_ready(out,in->len / 3 * 4 + 4)) return -1;
  s = out->s;

  for (i = 0;i < in->len;i += 3) {
    a = in->s[i];
    b = i + 1 < in->len ? in->s[i + 1] : 0;
    c = i + 2 < in->len ? in->s[i + 2] : 0;

    *s++ = b64alpha[a >> 2];
    *s++ = b64alpha[((a & 3 ) << 4) | (b >> 4)];

    if (i + 1 >= in->len) *s++ = B64PAD;
    else *s++ = b64alpha[((b & 15) << 2) | (c >> 6)];

    if (i + 2 >= in->len) *s++ = B64PAD;
    else *s++ = b64alpha[c & 63];
  }
  out->len = s - out->s;
  return 0;
}