/
githubmirror
/
nvme-cli
Обзор
Документация
Войти
/
githubmirror
/
nvme-cli
Код
Запросы
0
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
shared/base64.c
100 строк
2 KB
Mitsuru Kariya
base64: validate padding and trailing bits
04 авг 2026, 10:51
04 авг 2026, 10:51
6dc3536
Код
Авторство
О чём код?
// SPDX-License-Identifier: LGPL-2.1-or-later /* * base64.c - RFC4648-compliant base64 encoding * * This file is part of nvme-cli. * Copyright (c) 2020 SUSE LLC * * Author: Hannes Reinecke <hare@suse.de> */ #include <errno.h> #include <stdint.h> #include <string.h> #include "base64.h" static const char base64_table[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /** * shr_base64_encode() - base64-encode some bytes * @src: the bytes to encode * @srclen: number of bytes to encode * @dst: (output) the base64-encoded string. Not NUL-terminated. * * Encodes the input string using characters from the set [A-Za-z0-9+,]. * The encoded string is roughly 4/3 times the size of the input string. * * Return: length of the encoded string */ int shr_base64_encode(const unsigned char *src, int srclen, char *dst) { int i, bits = 0; uint32_t ac = 0; char *cp = dst; for (i = 0; i < srclen; i++) { ac = (ac << 8) | src[i]; bits += 8; do { bits -= 6; *cp++ = base64_table[(ac >> bits) & 0x3f]; } while (bits >= 6); } if (bits) { *cp++ = base64_table[(ac << (6 - bits)) & 0x3f]; bits -= 6; } while (bits < 0) { *cp++ = '='; bits += 2; } return cp - dst; } /** * shr_base64_decode() - base64-decode some bytes * @src: the base64-encoded string to decode * @srclen: number of bytes to decode * @dst: (output) the decoded bytes. * * Decodes the base64-encoded bytes @src according to RFC 4648, * including the '=' padding: @srclen has to be a multiple of four, and * a '=' anywhere other than in the trailing padding is rejected. * * Return: number of decoded bytes */ int shr_base64_decode(const char *src, int srclen, unsigned char *dst) { uint32_t ac = 0; int i, bits = 0, pad = 0; unsigned char *bp = dst; if (srclen < 0 || srclen % 4) return -EINVAL; while (srclen > 0 && src[srclen - 1] == '=') { if (++pad > 2) return -EINVAL; srclen--; } for (i = 0; i < srclen; i++) { const char *p = strchr(base64_table, src[i]); if (!p || !src[i]) return -EINVAL; ac = (ac << 6) | (p - base64_table); bits += 6; if (bits >= 8) { bits -= 8; *bp++ = (unsigned char)(ac >> bits); } } if (ac & ((1 << bits) - 1)) return -EINVAL; return bp - dst; }