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