[PATCH 04/11] lib/base64: RFC4648-compliant base64 encoding

Eric Biggers ebiggers at kernel.org
Sat Jul 17 07:20:51 PDT 2021


On Fri, Jul 16, 2021 at 01:04:21PM +0200, Hannes Reinecke wrote:
> +/**
> + * base64_decode() - base64-decode some bytes
> + * @src: the base64-encoded string to decode
> + * @len: number of bytes to decode
> + * @dst: (output) the decoded bytes.
> + *
> + * Decodes the base64-encoded bytes @src according to RFC 4648.
> + *
> + * Return: number of decoded bytes
> + */
> +int base64_decode(const char *src, int len, u8 *dst)
> +{
> +        int i, bits = 0, pad = 0;
> +        u32 ac = 0;
> +        size_t dst_len = 0;
> +
> +        for (i = 0; i < len; i++) {
> +                int c, p = -1;
> +
> +                if (src[i] == '=') {
> +                        pad++;
> +                        if (i + 1 < len && src[i + 1] == '=')
> +                                pad++;
> +                        break;
> +                }
> +                for (c = 0; c < strlen(lookup_table); c++) {
> +                        if (src[i] == lookup_table[c]) {
> +                                p = c;
> +                                break;
> +                        }
> +                }
> +                if (p < 0)
> +                        break;
> +                ac = (ac << 6) | p;
> +                bits += 6;
> +                if (bits < 24)
> +                        continue;
> +                while (bits) {
> +                        bits -= 8;
> +                        dst[dst_len++] = (ac >> bits) & 0xff;
> +                }
> +                ac = 0;
> +        }
> +        dst_len -= pad;
> +        return dst_len;
> +}
> +EXPORT_SYMBOL_GPL(base64_decode);

This should return an error if the input isn't valid base64.

- Eric



More information about the Linux-nvme mailing list