Ejemplo n.º 1
0
void
base64_encode (const char *const src, size_t srclen, char *const out, size_t *const outlen)
{
	size_t s;
	size_t t;
	struct base64_state state;

	/* Init the stream reader: */
	base64_stream_encode_init(&state);

	/* Feed the whole string to the stream reader: */
	base64_stream_encode(&state, src, srclen, out, &s);

	/* Finalize the stream by writing trailer if any: */
	base64_stream_encode_final(&state, out + s, &t);

	/* Final output length is stream length plus tail: */
	*outlen = s + t;
}
Ejemplo n.º 2
0
static int
test_streaming (int flags)
{
	bool fail = false;
	char chr[256];
	char ref[400], enc[400];
	size_t reflen;
	struct base64_state state;

	// Fill array with all characters 0..255:
	for (int i = 0; i < 256; i++)
		chr[i] = (unsigned char)i;

	// Create reference base64 encoding:
	base64_encode(chr, 256, ref, &reflen, BASE64_FORCE_PLAIN);

	// Encode the table with various block sizes and compare to reference:
	for (size_t bs = 1; bs < 255; bs++)
	{
		size_t inpos   = 0;
		size_t partlen = 0;
		size_t enclen  = 0;

		base64_stream_encode_init(&state, flags);
		memset(enc, 0, 400);
		for (;;) {
			base64_stream_encode(&state, &chr[inpos], (inpos + bs > 256) ? 256 - inpos : bs, &enc[enclen], &partlen);
			enclen += partlen;
			if (inpos + bs > 256) {
				break;
			}
			inpos += bs;
		}
		base64_stream_encode_final(&state, &enc[enclen], &partlen);
		enclen += partlen;

		if (enclen != reflen) {
			printf("FAIL: stream encoding gave incorrect size: "
				"%lu instead of %lu\n",
				(unsigned long)enclen,
				(unsigned long)reflen
			);
			fail = true;
		}
		if (strncmp(ref, enc, reflen) != 0) {
			printf("FAIL: stream encoding with blocksize %lu failed\n",
				(unsigned long)bs
			);
			fail = true;
		}
	}

	// Decode the reference encoding with various block sizes and
	// compare to input char table:
	for (size_t bs = 1; bs < 255; bs++)
	{
		size_t inpos   = 0;
		size_t partlen = 0;
		size_t enclen  = 0;

		base64_stream_decode_init(&state, flags);
		memset(enc, 0, 400);
		while (base64_stream_decode(&state, &ref[inpos], (inpos + bs > reflen) ? reflen - inpos : bs, &enc[enclen], &partlen)) {
			enclen += partlen;
			inpos += bs;
		}
		if (enclen != 256) {
			printf("FAIL: stream decoding gave incorrect size: "
				"%lu instead of 255\n",
				(unsigned long)enclen
			);
			fail = true;
		}
		if (strncmp(chr, enc, 256) != 0) {
			printf("FAIL: stream decoding with blocksize %lu failed\n",
				(unsigned long)bs
			);
			fail = true;
		}
	}

	return fail;
}