1 /* base64enc -- an encoder for base64
3 * Copyright (C) 2006, 2012 Jeronimo Pellegrini, Niels Möller
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU Lesser General Public License as published by
7 * the Free Software Foundation; either version 2.1 of the License, or (at your
8 * option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
13 * License for more details.
15 * You should have received a copy of the GNU Lesser General Public License
16 * along with the nettle library; see the file COPYING.LIB. If not, write to
17 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
37 /* The number of bytes read in each iteration, we do one line at a time: */
40 /* The *maximum* size of an encoded chunk: */
41 #define ENCODED_SIZE BASE64_ENCODE_LENGTH(CHUNK_SIZE)
44 * Reads bytes from standard input and writes base64-encoded
48 main(int argc UNUSED
, char **argv UNUSED
)
50 struct base64_encode_ctx b64_ctx
;
52 /* Init the context: */
53 base64_encode_init(&b64_ctx
);
56 _setmode(0, O_BINARY
);
61 /* "buffer" will hold the bytes from disk: */
62 uint8_t buffer
[CHUNK_SIZE
];
63 /* "result" is the result vector: */
64 uint8_t result
[ENCODED_SIZE
+ BASE64_ENCODE_FINAL_LENGTH
+ 1];
65 unsigned nbytes
; /* Number of bytes read from stdin */
66 int encoded_bytes
; /* total number of bytes encoded per iteration */
67 nbytes
= fread(buffer
,1,CHUNK_SIZE
,stdin
);
69 /* We overwrite result with more data */
70 encoded_bytes
= base64_encode_update(&b64_ctx
, result
, nbytes
, buffer
);
72 if (nbytes
< CHUNK_SIZE
)
76 werror ("Error reading file: %s\n", strerror(errno
));
79 encoded_bytes
+= base64_encode_final(&b64_ctx
,result
+ encoded_bytes
);
81 result
[encoded_bytes
++] = '\n';
82 if (!write_string (stdout
, encoded_bytes
, result
)
83 || fflush (stdout
) != 0)
85 werror ("Error writing file: %s\n", strerror(errno
));
91 /* The result vector is written */
92 result
[encoded_bytes
++] = '\n';
93 if (!write_string (stdout
, encoded_bytes
, result
))
95 werror ("Error writing file: %s\n", strerror(errno
));