1
0
mirror of https://git.tartarus.org/simon/putty.git synced 2025-01-09 01:18:00 +00:00
putty-source/utils/base64_encode.c
Simon Tatham 043c24844a Improve the base64 utility functions.
The low-level functions to handle a single atom of base64 at a time
have been in 'utils' / misc.h for ages, but the higher-level family of
base64_encode functions that handle a whole data block were hidden
away in sshpubk.c, and there was no higher-level decode function at
all.

Now moved both into 'utils' modules and declared them in misc.h rather
than ssh.h. Also, improved the APIs: they all take ptrlen in place of
separate data and length arguments, their naming is more consistent
and more explicit (the previous base64_encode which didn't name its
destination is now base64_encode_fp), and the encode functions now
accept cpl == 0 as a special case meaning that the output base64 data
is wanted in the form of an unbroken single-line string with no
trailing \n.
2022-04-25 14:10:16 +01:00

41 lines
1008 B
C

#include "misc.h"
void base64_encode_bs(BinarySink *bs, ptrlen input, int cpl)
{
BinarySource src[1];
BinarySource_BARE_INIT_PL(src, input);
int linelen = 0;
while (get_avail(src)) {
size_t n = get_avail(src) < 3 ? get_avail(src) : 3;
ptrlen binatom = get_data(src, n);
char b64atom[4];
base64_encode_atom(binatom.ptr, binatom.len, b64atom);
for (size_t i = 0; i < 4; i++) {
if (cpl > 0 && linelen >= cpl) {
linelen = 0;
put_byte(bs, '\n');
}
put_byte(bs, b64atom[i]);
linelen++;
}
}
if (cpl > 0)
put_byte(bs, '\n');
}
void base64_encode_fp(FILE *fp, ptrlen input, int cpl)
{
stdio_sink ss;
stdio_sink_init(&ss, fp);
base64_encode_bs(BinarySink_UPCAST(&ss), input, cpl);
}
strbuf *base64_encode_sb(ptrlen input, int cpl)
{
strbuf *sb = strbuf_new_nm();
base64_encode_bs(BinarySink_UPCAST(sb), input, cpl);
return sb;
}