1 /* compliant base64 code donated by Wayne Scott (wscott@bitmover.com) */
6 static const char *codes =
7 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
9 static const unsigned char map[256] = {
10 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
11 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
12 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
13 255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63,
14 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255,
15 255, 254, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6,
16 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
17 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255,
18 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
19 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
20 49, 50, 51, 255, 255, 255, 255, 255, 255, 255, 255, 255,
21 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
22 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
23 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
24 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
25 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
26 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
27 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
28 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
29 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
30 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
33 int base64_encode(const unsigned char *in, unsigned long len,
34 unsigned char *out, unsigned long *outlen)
36 unsigned long i, len2, leven;
41 _ARGCHK(outlen != NULL);
43 /* valid output size ? */
44 len2 = 4 * ((len + 2) / 3);
45 if (*outlen < len2 + 1) {
46 return CRYPT_BUFFER_OVERFLOW;
50 for (i = 0; i < leven; i += 3) {
51 *p++ = codes[in[0] >> 2];
52 *p++ = codes[((in[0] & 3) << 4) + (in[1] >> 4)];
53 *p++ = codes[((in[1] & 0xf) << 2) + (in[2] >> 6)];
54 *p++ = codes[in[2] & 0x3f];
57 /* Pad it if necessary... */
60 unsigned b = (i+1 < len) ? in[1] : 0;
64 *p++ = codes[((a & 3) << 4) + (b >> 4)];
65 *p++ = (i+1 < len) ? codes[((b & 0xf) << 2) + (c >> 6)] : '=';
69 /* append a NULL byte */
77 int base64_decode(const unsigned char *in, unsigned long len,
78 unsigned char *out, unsigned long *outlen)
80 unsigned long t, x, y, z;
86 _ARGCHK(outlen != NULL);
88 for (x = y = z = t = 0; x < len; x++) {
90 if (c == 255) continue;
91 if (c == 254) { c = 0; g--; }
94 if (z + g > *outlen) { return CRYPT_BUFFER_OVERFLOW; }
95 out[z++] = (unsigned char)((t>>16)&255);
96 if (g > 1) out[z++] = (unsigned char)((t>>8)&255);
97 if (g > 2) out[z++] = (unsigned char)(t&255);
102 return CRYPT_INVALID_PACKET;