2 * base64.c -- routines for converting to base64
4 * This code is Copyright (c) 2012, by the authors of nmh. See the
5 * COPYRIGHT file in the root directory of the nmh distribution for
6 * complete copyright information.
12 static char nib2b64[0x40+1] =
13 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
16 writeBase64aux (FILE *in, FILE *out)
22 while ((cc = fread (inbuf, sizeof(*inbuf), sizeof(inbuf), in)) > 0) {
27 if (cc < sizeof(inbuf)) {
29 if (cc < sizeof(inbuf) - 1)
32 bits = (inbuf[0] & 0xff) << 16;
33 bits |= (inbuf[1] & 0xff) << 8;
34 bits |= inbuf[2] & 0xff;
36 for (bp = outbuf + sizeof(outbuf); bp > outbuf; bits >>= 6)
37 *--bp = nib2b64[bits & 0x3f];
38 if (cc < sizeof(inbuf)) {
40 if (cc < sizeof inbuf - 1)
44 fwrite (outbuf, sizeof(*outbuf), sizeof(outbuf), out);
46 if (cc < sizeof(inbuf)) {
63 /* Caller is responsible for ensuring that the out array is long
64 enough. Given length is that of in, out should be have at
66 4 * [length/3] + length/57 + 2
67 But double the length will certainly be sufficient. */
69 writeBase64 (unsigned char *in, size_t length, unsigned char *out)
71 unsigned int n = BPERLIN;
77 for (cc = 0, bp = in; length > 0 && cc < 3; ++cc, ++bp, --length)
83 bits = (in[0] & 0xff) << 16;
85 bits |= (in[1] & 0xff) << 8;
92 for (bp = out + 4; bp > out; bits >>= 6)
93 *--bp = nib2b64[bits & 0x3f];