lib/base64.c

Source file repositories/reference/linux-study-clean/lib/base64.c

File Facts

System
Linux kernel
Corpus path
lib/base64.c
Extension
.c
Size
5351 bytes
Lines
186
Domain
Kernel Services
Bucket
lib
Inferred role
Kernel Services: exported/initcall integration point
Status
integration implementation candidate

Why This File Exists

Shared kernel service surface used by multiple subsystems, including helpers, cryptography, virtualization support, and async I/O infrastructure.

Dependency Surface

Detected Declarations

Annotated Snippet

if (padding) {
			*cp++ = '=';
			*cp++ = '=';
		}
		break;
	}
	return cp - dst;
}
EXPORT_SYMBOL_GPL(base64_encode);

/**
 * base64_decode() - Base64-decode a string
 * @src: the string to decode.  Doesn't need to be NUL-terminated.
 * @srclen: the length of @src in bytes
 * @dst: (output) the decoded binary data
 * @padding: whether the input is expected to include '=' padding characters
 * @variant: which base64 variant to use
 *
 * Decodes a string using the selected Base64 variant.
 *
 * Return: the length of the resulting decoded binary data in bytes,
 *	   or -1 if the string isn't a valid Base64 string.
 */
int base64_decode(const char *src, int srclen, u8 *dst, bool padding, enum base64_variant variant)
{
	u8 *bp = dst;
	s8 input[4];
	s32 val;
	const u8 *s = (const u8 *)src;
	const s8 *base64_rev_tables = base64_rev_maps[variant];

	while (srclen >= 4) {
		input[0] = base64_rev_tables[s[0]];
		input[1] = base64_rev_tables[s[1]];
		input[2] = base64_rev_tables[s[2]];
		input[3] = base64_rev_tables[s[3]];

		val = input[0] << 18 | input[1] << 12 | input[2] << 6 | input[3];

		if (unlikely(val < 0)) {
			if (!padding || srclen != 4 || s[3] != '=')
				return -1;
			padding = 0;
			srclen = s[2] == '=' ? 2 : 3;
			break;
		}

		*bp++ = val >> 16;
		*bp++ = val >> 8;
		*bp++ = val;

		s += 4;
		srclen -= 4;
	}

	if (likely(!srclen))
		return bp - dst;
	if (padding || srclen == 1)
		return -1;

	val = (base64_rev_tables[s[0]] << 12) | (base64_rev_tables[s[1]] << 6);

	if (srclen == 2) {
		if (val & 0x800003ff)
			return -1;
		*bp++ = val >> 10;
	} else {
		val |= base64_rev_tables[s[2]];
		if (val & 0x80000003)
			return -1;
		*bp++ = val >> 10;
		*bp++ = val >> 2;
	}
	return bp - dst;
}
EXPORT_SYMBOL_GPL(base64_decode);

Annotation

Implementation Notes