1 /* base64enc -- an encoder for base64
3 Copyright (C) 2006, 2012 Jeronimo Pellegrini, Niels Möller
5 This file is part of GNU Nettle.
7 GNU Nettle is free software: you can redistribute it and/or
8 modify it under the terms of either:
10 * the GNU Lesser General Public License as published by the Free
11 Software Foundation; either version 3 of the License, or (at your
12 option) any later version.
16 * the GNU General Public License as published by the Free
17 Software Foundation; either version 2 of the License, or (at your
18 option) any later version.
20 or both in parallel, as here.
22 GNU Nettle is distributed in the hope that it will be useful,
23 but WITHOUT ANY WARRANTY; without even the implied warranty of
24 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
25 General Public License for more details.
27 You should have received copies of the GNU General Public License and
28 the GNU Lesser General Public License along with this program. If
29 not, see http://www.gnu.org/licenses/.
48 /* The number of bytes read in each iteration, we do one line at a time: */
51 /* The *maximum* size of an encoded chunk: */
52 #define ENCODED_SIZE BASE64_ENCODE_LENGTH(CHUNK_SIZE)
55 * Reads bytes from standard input and writes base64-encoded
59 main(int argc UNUSED, char **argv UNUSED)
61 struct base64_encode_ctx b64_ctx;
63 /* Init the context: */
64 base64_encode_init(&b64_ctx);
67 _setmode(0, O_BINARY);
72 /* "buffer" will hold the bytes from disk: */
73 uint8_t buffer[CHUNK_SIZE];
74 /* "result" is the result vector: */
75 uint8_t result[ENCODED_SIZE + BASE64_ENCODE_FINAL_LENGTH + 1];
76 unsigned nbytes; /* Number of bytes read from stdin */
77 int encoded_bytes; /* total number of bytes encoded per iteration */
78 nbytes = fread(buffer,1,CHUNK_SIZE,stdin);
80 /* We overwrite result with more data */
81 encoded_bytes = base64_encode_update(&b64_ctx, result, nbytes, buffer);
83 if (nbytes < CHUNK_SIZE)
87 werror ("Error reading file: %s\n", strerror(errno));
90 encoded_bytes += base64_encode_final(&b64_ctx,result + encoded_bytes);
92 result[encoded_bytes++] = '\n';
93 if (!write_string (stdout, encoded_bytes, result)
94 || fflush (stdout) != 0)
96 werror ("Error writing file: %s\n", strerror(errno));
102 /* The result vector is written */
103 result[encoded_bytes++] = '\n';
104 if (!write_string (stdout, encoded_bytes, result))
106 werror ("Error writing file: %s\n", strerror(errno));