[OpenWrt-Devel] [PATCH] [libubox][v4] b64: add base64 support

Luka Perkov luka at openwrt.org
Sat Apr 18 20:32:54 EDT 2015


On Fri, Apr 17, 2015 at 02:14:14AM +0200, Felix Fietkau wrote:
> > +size_t b64decode(void *out, const void *in, size_t len)
> > +{
> > +	uint8_t *o = (uint8_t *) out;
> > +	const uint8_t *data = (const uint8_t *) in;
> > +	size_t lenout, i, j;
> > +	uint32_t cv = 0;
> > +
> > +	lenout = b64_decode_size(len);
> > +	if (!lenout)
> > +		return 0;
> > +
> > +	o[--lenout] = '\0';
> > +
> > +	for (i = 0; i < len; i += 4) {
> > +		cv = 0;
> > +		for (j = 0; j < 4; j++) {
> > +			uint8_t c = data[i + j] - 43;
> > +			if (c > 79 || (c = b64decode_tbl[c]) == 0xff)
> > +				return 0;
> > +
> > +			cv |= c;
> > +			if (j != 3)
> > +				cv <<= 6;
> > +		}
> > +
> > +		o[2] = (uint8_t)(cv & 0xff);
> > +		o[1] = (uint8_t)((cv >> 8) & 0xff);
> > +		o[0] = (uint8_t)((cv >> 16) & 0xff);
> > +		o += 3;
> > +	}
> > +
> > +	for (i = 1; i <= 2; i++) {
> > +		if (data[len - i] == '=') {
> > +			o[-i] = '\0';
> > +			lenout--;
> > +		} else
> > +			break;
> > +	}
> I think this function should match the capabilities and return code of
> b64_pton from BSD.
> It should return an int (or ssize_t) instead of size_t, and return -1 on
> errors. It should also be able to skip whitespaces.

I've chaned API as requested but there is no easy way of adding support
for whitespaces current b64decode() function. So if you really want
support for whitespaces as well as the same capabilities and return
codes I am proposing that we take in function from BSD instead of this
one. Please let me know.

> > +static const uint8_t b64encode_tbl[] =
> > +	"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
> > +
> > +size_t b64encode(void *out, const void *in, size_t len)
> > +{
> > +	uint8_t *o = (uint8_t *) out;
> > +	const uint8_t *data = (const uint8_t *) in;
> > +	size_t lenout, pad, i;
> > +	uint32_t cv;
> > +
> > +	lenout = b64_encode_size(len);
> > +	if (!lenout)
> > +		return 0;
> Why call b64_encode_size instead of just setting *o = 0 at the end of
> the function?

Fixed in v5 which I've sent few moments ago.

Luka
_______________________________________________
openwrt-devel mailing list
openwrt-devel at lists.openwrt.org
https://lists.openwrt.org/cgi-bin/mailman/listinfo/openwrt-devel



More information about the openwrt-devel mailing list