|
| 1 | +// SPDX-License-Identifier: GPL-2.0-or-later |
| 2 | +/* |
| 3 | + * base64.c - RFC4648-compliant base64 encoding |
| 4 | + * |
| 5 | + * Copyright (c) 2020 SUSE LLC |
| 6 | + * |
| 7 | + * Author: Hannes Reinecke <[email protected]> |
| 8 | + */ |
| 9 | + |
| 10 | +#include <stdlib.h> |
| 11 | +#include <string.h> |
| 12 | +#include <errno.h> |
| 13 | +#include <sys/types.h> |
| 14 | + |
| 15 | +static const char base64_table[65] = |
| 16 | + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; |
| 17 | + |
| 18 | +/** |
| 19 | + * base64_encode() - base64-encode some bytes |
| 20 | + * @src: the bytes to encode |
| 21 | + * @srclen: number of bytes to encode |
| 22 | + * @dst: (output) the base64-encoded string. Not NUL-terminated. |
| 23 | + * |
| 24 | + * Encodes the input string using characters from the set [A-Za-z0-9+,]. |
| 25 | + * The encoded string is roughly 4/3 times the size of the input string. |
| 26 | + * |
| 27 | + * Return: length of the encoded string |
| 28 | + */ |
| 29 | +int base64_encode(const unsigned char *src, int srclen, char *dst) |
| 30 | +{ |
| 31 | + int i, bits = 0; |
| 32 | + u_int32_t ac = 0; |
| 33 | + char *cp = dst; |
| 34 | + |
| 35 | + for (i = 0; i < srclen; i++) { |
| 36 | + ac = (ac << 8) | src[i]; |
| 37 | + bits += 8; |
| 38 | + do { |
| 39 | + bits -= 6; |
| 40 | + *cp++ = base64_table[(ac >> bits) & 0x3f]; |
| 41 | + } while (bits >= 6); |
| 42 | + } |
| 43 | + if (bits) { |
| 44 | + *cp++ = base64_table[(ac << (6 - bits)) & 0x3f]; |
| 45 | + bits -= 6; |
| 46 | + } |
| 47 | + while (bits < 0) { |
| 48 | + *cp++ = '='; |
| 49 | + bits += 2; |
| 50 | + } |
| 51 | + |
| 52 | + return cp - dst; |
| 53 | +} |
| 54 | + |
| 55 | +/** |
| 56 | + * base64_decode() - base64-decode some bytes |
| 57 | + * @src: the base64-encoded string to decode |
| 58 | + * @len: number of bytes to decode |
| 59 | + * @dst: (output) the decoded bytes. |
| 60 | + * |
| 61 | + * Decodes the base64-encoded bytes @src according to RFC 4648. |
| 62 | + * |
| 63 | + * Return: number of decoded bytes |
| 64 | + */ |
| 65 | +int base64_decode(const char *src, int srclen, unsigned char *dst) |
| 66 | +{ |
| 67 | + u_int32_t ac = 0; |
| 68 | + int i, bits = 0; |
| 69 | + unsigned char *bp = dst; |
| 70 | + |
| 71 | + for (i = 0; i < srclen; i++) { |
| 72 | + const char *p = strchr(base64_table, src[i]); |
| 73 | + |
| 74 | + if (src[i] == '=') { |
| 75 | + ac = (ac << 6); |
| 76 | + bits += 6; |
| 77 | + if (bits >= 8) |
| 78 | + bits -= 8; |
| 79 | + continue; |
| 80 | + } |
| 81 | + if (!p || !src[i]) |
| 82 | + return -EINVAL; |
| 83 | + ac = (ac << 6) | (p - base64_table); |
| 84 | + bits += 6; |
| 85 | + if (bits >= 8) { |
| 86 | + bits -= 8; |
| 87 | + *bp++ = (unsigned char)(ac >> bits); |
| 88 | + } |
| 89 | + } |
| 90 | + if (ac && ((1 << bits) - 1)) |
| 91 | + return -EAGAIN; |
| 92 | + |
| 93 | + return bp - dst; |
| 94 | +} |
0 commit comments