1 /* base64dec -- an decoder 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 #define CHUNK_SIZE 16392
50 /* The maximum number of bytes generated for each chunk: */
51 #define DECODED_SIZE BASE64_DECODE_LENGTH(CHUNK_SIZE)
55 * Reads base-64 encoded from stdin, writes decoded to stdout.
58 main(int argc UNUSED, char **argv UNUSED)
60 /* "buffer" will hold the bytes from disk: */
61 uint8_t * buffer = xalloc (CHUNK_SIZE);
63 /* "result" will hold bytes before output: */
64 uint8_t * result = xalloc (DECODED_SIZE);
66 /* We need a Base64 context for decoding: */
67 struct base64_decode_ctx b64_ctx;
69 /* Init the context: */
70 base64_decode_init(&b64_ctx);
73 _setmode(1, O_BINARY);
78 int nbytes; /* Number of bytes read frmo disk at each iteration */
79 size_t decoded_bytes; /* Bytes actually generated at each iteration */
81 nbytes = fread(buffer, 1, CHUNK_SIZE, stdin);
83 if (nbytes < CHUNK_SIZE && ferror(stdin))
85 werror ("Error reading file: %s\n", strerror(errno));
89 /* Decodes one chunk: */
90 if (!base64_decode_update(&b64_ctx, &decoded_bytes, result, nbytes, buffer))
92 werror ("Error decoding input (not base64?)\n");
96 if (!write_string (stdout, decoded_bytes, result))
98 werror ("Error writing file: %s\n", strerror(errno));
102 if (nbytes < CHUNK_SIZE)
104 /* Check if decoding finalized OK: */
105 if (!base64_decode_final(&b64_ctx))
107 werror ("Decoding did not finish properly.\n");
114 if (fflush (stdout) != 0)
116 werror ("Error writing file: %s\n", strerror(errno));