summaryrefslogtreecommitdiff
path: root/lib/tar/base64.c
blob: f88444ad3924a72f724b9b27d143619b5a209d68 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/* SPDX-License-Identifier: GPL-3.0-or-later */
/*
 * base64.c
 *
 * Copyright (C) 2019 David Oberhollenzer <goliath@infraroot.at>
 */
#include "config.h"

#include "internal.h"

static sqfs_u8 convert(char in)
{
	if (isupper(in))
		return in - 'A';
	if (islower(in))
		return in - 'a' + 26;
	if (isdigit(in))
		return in - '0' + 52;
	if (in == '+')
		return 62;
	if (in == '/' || in == '-')
		return 63;
	return 0;
}

size_t base64_decode(sqfs_u8 *out, const char *in, size_t len)
{
	sqfs_u8 *start = out;

	while (len > 0) {
		unsigned int diff = 0, value = 0;

		while (diff < 4 && len > 0) {
			if (*in == '=' || *in == '_' || *in == '\0') {
				len = 0;
			} else {
				value = (value << 6) | convert(*(in++));
				--len;
				++diff;
			}
		}

		if (diff < 2)
			break;

		value <<= 6 * (4 - diff);

		switch (diff) {
		case 4:  out[2] = value & 0xff; /* fall-through */
		case 3:  out[1] = (value >> 8) & 0xff; /* fall-through */
		default: out[0] = (value >> 16) & 0xff;
		}

		out += (diff * 3) / 4;
	}

	*out = '\0';
	return out - start;
}