diff --git a/include/Void/Text/Base32.hpp b/include/Void/Text/Base32.hpp new file mode 100644 index 0000000..b3f976b --- /dev/null +++ b/include/Void/Text/Base32.hpp @@ -0,0 +1,273 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Encoding::Base32 +{ + + namespace Detail + { + /// RFC 4648 section 6 alphabet. + constexpr std::string_view alphabet = + "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + + /// Crockford alphabet: no I, L, O or U. + constexpr std::string_view alphabet_crockford = + "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; + + constexpr char to_lower_ascii(char c) noexcept + { + return (c >= 'A' && c <= 'Z') ? static_cast(c + ('a' - 'A')) : c; + } + + [[nodiscard]] constexpr std::array + make_rfc_table() noexcept + { + std::array t{}; + t.fill(-1); + for (std::size_t i = 0; i < 32; ++i) { + const char upper = alphabet[i]; + t[static_cast(upper)] = + static_cast(i); + t[static_cast(to_lower_ascii(upper))] = + static_cast(i); + } + return t; + } + + [[nodiscard]] constexpr std::array + make_crockford_table() noexcept + { + std::array t{}; + t.fill(-1); + for (std::size_t i = 0; i < 32; ++i) { + const char upper = alphabet_crockford[i]; + t[static_cast(upper)] = + static_cast(i); + t[static_cast(to_lower_ascii(upper))] = + static_cast(i); + } + // Crockford aliases: I and L are 1, O is 0. + for (const char c : {'I', 'i', 'L', 'l'}) { + t[static_cast(c)] = 1; + } + for (const char c : {'O', 'o'}) { + t[static_cast(c)] = 0; + } + // U is deliberately absent (rejected). + return t; + } + + /// Overwrite partial output before discarding it so a failed decode + /// does not leave decoded plaintext behind in freed storage. + inline void wipe(std::string& out) noexcept + { + std::fill(out.begin(), out.end(), '\0'); + out.clear(); + } + + inline std::string encode_with(std::span data, + std::string_view alpha, + bool pad) + { + std::string out; + out.reserve(((data.size() + 4) / 5) * 8); + std::uint32_t buffer = 0; + int bits = 0; + for (const std::byte raw : data) { + buffer = (buffer << 8) | + static_cast( + static_cast(raw)); + bits += 8; + while (bits >= 5) { + bits -= 5; + out += alpha[(buffer >> bits) & 0x1FU]; + } + buffer &= bits == 0 ? 0U : ((1U << bits) - 1U); + } + if (bits != 0) { + out += alpha[(buffer << (5 - bits)) & 0x1FU]; + } + if (pad) { + while (out.size() % 8 != 0) { + out += '='; + } + } + return out; + } + + inline std::optional + decode_with(std::string_view s, + const std::array& table, + bool allow_padding, + bool skip_separators, + Void::Text::TextLimits limits) + { + if (s.size() > limits.max_input) { + return std::nullopt; + } + + std::string out; + out.reserve((s.size() * 5) / 8); + + std::uint32_t buffer = 0; + int bits = 0; + std::size_t symbols = 0; + std::size_t padding = 0; + bool saw_padding = false; + + for (const char encoded : s) { + const auto character = static_cast(encoded); + if (skip_separators && encoded == '-') { + continue; + } + if (allow_padding && encoded == '=') { + saw_padding = true; + ++padding; + continue; + } + if (saw_padding) { + wipe(out); + return std::nullopt; + } + + const std::int8_t value = table[character]; + if (value < 0) { + wipe(out); + return std::nullopt; + } + + buffer = (buffer << 5) | static_cast(value); + bits += 5; + ++symbols; + if (bits >= 8) { + bits -= 8; + out += static_cast((buffer >> bits) & 0xFFU); + if (out.size() > limits.max_output) { + wipe(out); + return std::nullopt; + } + buffer &= bits == 0 ? 0U : ((1U << bits) - 1U); + } + } + + const std::size_t remainder = symbols % 8; + if (remainder == 1 || remainder == 3 || remainder == 6) { + wipe(out); + return std::nullopt; + } + const std::size_t expected_padding = + remainder == 0 ? 0 : 8 - remainder; + if (padding != 0 && padding != expected_padding) { + wipe(out); + return std::nullopt; + } + // Non-zero trailing pad bits mean the text is not canonical. + if (bits != 0 && buffer != 0) { + wipe(out); + return std::nullopt; + } + return out; + } + } // namespace Detail + + /// Encode bytes to RFC 4648 Base32 (uppercase, with padding). + [[nodiscard]] inline std::string encode(std::span data) + { + return Detail::encode_with(data, Detail::alphabet, true); + } + + /// Encode an unsigned-byte view without forcing callers to reinterpret + /// their binary buffers as text. + [[nodiscard]] inline std::string encode(std::span data) + { + return encode(std::as_bytes(data)); + } + + /// Encode a string_view to RFC 4648 Base32. + [[nodiscard]] inline std::string encode(std::string_view s) + { + return encode(std::as_bytes(std::span{s.data(), s.size()})); + } + + /// Decode RFC 4648 Base32. Accepts padded or unpadded text and is + /// case-insensitive. Returns nullopt for invalid characters, impossible + /// lengths, malformed padding, non-zero trailing bits, or limits exceeded. + [[nodiscard]] inline std::optional + decode(std::string_view s, Void::Text::TextLimits limits = {}) + { + static constexpr auto table = Detail::make_rfc_table(); + return Detail::decode_with( + s, table, /*allow_padding=*/true, /*skip_separators=*/false, limits); + } + + /// Decode RFC 4648 Base32 into an explicitly binary buffer. + [[nodiscard]] inline std::optional> + decode_bytes(std::string_view s, Void::Text::TextLimits limits = {}) + { + const auto decoded = decode(s, limits); + if (!decoded) { + return std::nullopt; + } + + const auto bytes = + std::as_bytes(std::span{decoded->data(), decoded->size()}); + return std::vector{bytes.begin(), bytes.end()}; + } + + /// Encode bytes to Crockford Base32 (uppercase, no padding). + [[nodiscard]] inline std::string + encode_crockford(std::span data) + { + return Detail::encode_with(data, Detail::alphabet_crockford, false); + } + + [[nodiscard]] inline std::string + encode_crockford(std::span data) + { + return encode_crockford(std::as_bytes(data)); + } + + [[nodiscard]] inline std::string encode_crockford(std::string_view s) + { + return encode_crockford(std::as_bytes(std::span{s.data(), s.size()})); + } + + /// Decode Crockford Base32. Case-insensitive; I/L map to 1, O maps to 0, + /// U is rejected, and '-' separators are skipped. Returns nullopt on + /// invalid input, impossible lengths, non-zero trailing bits, or limits + /// exceeded. + [[nodiscard]] inline std::optional + decode_crockford(std::string_view s, Void::Text::TextLimits limits = {}) + { + static constexpr auto table = Detail::make_crockford_table(); + return Detail::decode_with( + s, table, /*allow_padding=*/false, /*skip_separators=*/true, limits); + } + + /// Decode Crockford Base32 into an explicitly binary buffer. + [[nodiscard]] inline std::optional> + decode_crockford_bytes(std::string_view s, + Void::Text::TextLimits limits = {}) + { + const auto decoded = decode_crockford(s, limits); + if (!decoded) { + return std::nullopt; + } + + const auto bytes = + std::as_bytes(std::span{decoded->data(), decoded->size()}); + return std::vector{bytes.begin(), bytes.end()}; + } + +} // namespace Void::Encoding::Base32 diff --git a/tests/standalone/Text/Base32.cpp b/tests/standalone/Text/Base32.cpp new file mode 100644 index 0000000..edd5349 --- /dev/null +++ b/tests/standalone/Text/Base32.cpp @@ -0,0 +1,291 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + using Void::Encoding::Base32::decode; + using Void::Encoding::Base32::decode_bytes; + using Void::Encoding::Base32::decode_crockford; + using Void::Encoding::Base32::encode; + using Void::Encoding::Base32::encode_crockford; + + std::string strip_padding(std::string text) + { + while (!text.empty() && text.back() == '=') { + text.pop_back(); + } + return text; + } + + std::string lowercase(std::string text) + { + for (char& c : text) { + if (c >= 'A' && c <= 'Z') { + c = static_cast(c + ('a' - 'A')); + } + } + return text; + } + + std::string pattern(std::size_t size) + { + std::string out; + out.reserve(size); + for (std::size_t i = 0; i < size; ++i) { + out.push_back(static_cast((i * 37 + 11) & 0xFF)); + } + return out; + } + + std::array five_bytes(std::uint64_t value) + { + std::array bytes{}; + for (std::size_t i = 0; i < bytes.size(); ++i) { + bytes[i] = static_cast( + (value >> (8 * (bytes.size() - 1 - i))) & 0xFF); + } + return bytes; + } + + std::string as_text(const std::array& bytes) + { + return std::string{reinterpret_cast(bytes.data()), + bytes.size()}; + } +} // namespace + +// ── RFC 4648 ──────────────────────────────────────────────────────────────── + +Void::Testing::Test base32_rfc4648_section10_vectors() +{ + struct Vector + { + std::string_view plain; + std::string_view encoded; + }; + constexpr std::array vectors{ + Vector{"", ""}, + Vector{"f", "MY======"}, + Vector{"fo", "MZXQ===="}, + Vector{"foo", "MZXW6==="}, + Vector{"foob", "MZXW6YQ="}, + Vector{"fooba", "MZXW6YTB"}, + Vector{"foobar", "MZXW6YTBOI======"}, + }; + + for (const auto& [plain, encoded] : vectors) { + const std::string padded{encoded}; + const std::string unpadded = strip_padding(padded); + + Void::Testing::expect_eq(encode(plain), padded); + + const auto padded_decoded = decode(padded); + Void::Testing::require(padded_decoded.has_value()); + Void::Testing::expect_eq(*padded_decoded, std::string{plain}); + + const auto unpadded_decoded = decode(unpadded); + Void::Testing::require(unpadded_decoded.has_value()); + Void::Testing::expect_eq(*unpadded_decoded, std::string{plain}); + + const auto lower_decoded = decode(lowercase(padded)); + Void::Testing::require(lower_decoded.has_value()); + Void::Testing::expect_eq(*lower_decoded, std::string{plain}); + + const auto lower_unpadded_decoded = decode(lowercase(unpadded)); + Void::Testing::require(lower_unpadded_decoded.has_value()); + Void::Testing::expect_eq(*lower_unpadded_decoded, std::string{plain}); + } +} + +Void::Testing::Test base32_rfc4648_every_alphabet_symbol() +{ + constexpr std::string_view alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + for (std::uint64_t value = 0; value < 32; ++value) { + std::uint64_t packed = 0; + for (int group = 0; group < 8; ++group) { + packed = (packed << 5) | value; + } + const auto bytes = five_bytes(packed); + const std::string text = as_text(bytes); + + const std::string encoded = encode(std::span{bytes}); + Void::Testing::expect_eq(encoded, std::string(8, alphabet[value])); + + const auto decoded = decode(encoded); + Void::Testing::require(decoded.has_value()); + Void::Testing::expect_eq(*decoded, text); + } +} + +Void::Testing::Test base32_rfc4648_rejects_invalid_text() +{ + // Invalid characters (including whitespace, which is not skipped). + for (const std::string_view text : {"MZ$Q====", + "MZXW6YT!", + "MY======\n", + " MY====="}) { + Void::Testing::expect(!decode(text).has_value()); + } + + // Impossible symbol counts: remainder 1, 3 and 6 modulo 8. + for (const std::string_view text : {"M", "MZX", "MZXW6Y"}) { + Void::Testing::expect(!decode(text).has_value()); + } + + // Malformed padding. + for (const std::string_view text : + {"MY=====", "MY=======", "M=======", "MY=====A", "MY=A====", + "MZXW6Y=", "MZXW6YTB="}) { + Void::Testing::expect(!decode(text).has_value()); + } + + // Non-zero trailing pad bits for every remainder class. + for (const std::string_view text : {"MZ======", "MZXR", "MZXW7", "MZXW6YR"}) { + Void::Testing::expect(!decode(text).has_value()); + } + + // The empty text is valid and decodes to nothing. + const auto empty = decode(""); + Void::Testing::require(empty.has_value()); + Void::Testing::expect(empty->empty()); +} + +Void::Testing::Test base32_rfc4648_round_trips() +{ + constexpr std::array boundaries{ + 1, 2, 3, 4, 5, 6, 9, 10, 11, + 15, 16, 17, 31, 32, 33, 100, 255, 1024}; + + for (std::size_t size = 0; size <= 64; ++size) { + const std::string original = pattern(size); + const std::string encoded = encode(original); + + const auto padded = decode(encoded); + Void::Testing::require(padded.has_value()); + Void::Testing::expect_eq(*padded, original); + + const auto unpadded = decode(strip_padding(encoded)); + Void::Testing::require(unpadded.has_value()); + Void::Testing::expect_eq(*unpadded, original); + + const auto lower = decode(lowercase(encoded)); + Void::Testing::require(lower.has_value()); + Void::Testing::expect_eq(*lower, original); + + const auto bytes = decode_bytes(encoded); + Void::Testing::require(bytes.has_value()); + Void::Testing::expect_eq(bytes->size(), original.size()); + } + + for (const std::size_t size : boundaries) { + const std::string original = pattern(size); + const auto decoded = decode(encode(original)); + Void::Testing::require(decoded.has_value()); + Void::Testing::expect_eq(*decoded, original); + + const auto crockford = decode_crockford(encode_crockford(original)); + Void::Testing::require(crockford.has_value()); + Void::Testing::expect_eq(*crockford, original); + } +} + +// ── Crockford ─────────────────────────────────────────────────────────────── + +Void::Testing::Test base32_crockford_aliases_and_separators() +{ + const auto one = decode_crockford("10"); + const auto zero = decode_crockford("00"); + Void::Testing::require(one.has_value()); + Void::Testing::require(zero.has_value()); + + for (const std::string_view alias : {"I0", "L0", "i0", "l0"}) { + const auto decoded = decode_crockford(alias); + Void::Testing::require(decoded.has_value()); + Void::Testing::expect_eq(*decoded, *one); + } + for (const std::string_view alias : {"O0", "o0"}) { + const auto decoded = decode_crockford(alias); + Void::Testing::require(decoded.has_value()); + Void::Testing::expect_eq(*decoded, *zero); + } + + const auto separated = decode_crockford("A-B-C0"); + const auto plain = decode_crockford("ABC0"); + Void::Testing::require(separated.has_value()); + Void::Testing::require(plain.has_value()); + Void::Testing::expect_eq(*separated, *plain); + + // U is rejected, as are other invalid characters and padding. + for (const std::string_view text : {"U0", "u0", "!0", "AB==", "01"}) { + Void::Testing::expect(!decode_crockford(text).has_value()); + } +} + +Void::Testing::Test base32_crockford_every_alphabet_symbol() +{ + constexpr std::string_view alphabet = + "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; + for (std::uint64_t value = 0; value < 32; ++value) { + std::uint64_t packed = 0; + for (int group = 0; group < 8; ++group) { + packed = (packed << 5) | value; + } + const auto bytes = five_bytes(packed); + const std::string text = as_text(bytes); + + const std::string encoded = + encode_crockford(std::span{bytes}); + Void::Testing::expect_eq(encoded, std::string(8, alphabet[value])); + + const auto decoded = decode_crockford(encoded); + Void::Testing::require(decoded.has_value()); + Void::Testing::expect_eq(*decoded, text); + } +} + +Void::Testing::Test base32_crockford_round_trips() +{ + for (std::size_t size = 0; size <= 64; ++size) { + const std::string original = pattern(size); + const std::string encoded = encode_crockford(original); + Void::Testing::expect(encoded.find('=') == std::string::npos); + + const auto decoded = decode_crockford(encoded); + Void::Testing::require(decoded.has_value()); + Void::Testing::expect_eq(*decoded, original); + + const auto lower = decode_crockford(lowercase(encoded)); + Void::Testing::require(lower.has_value()); + Void::Testing::expect_eq(*lower, original); + } +} + +// ── Bounds ────────────────────────────────────────────────────────────────── + +Void::Testing::Test base32_respects_text_limits() +{ + using Void::Text::TextLimits; + + const std::string valid = "MZXW6YTB"; // 5 decoded bytes + Void::Testing::expect(decode(valid).has_value()); + Void::Testing::expect(!decode(valid, TextLimits{.max_input = 7}).has_value()); + Void::Testing::expect( + !decode(valid, TextLimits{.max_output = 4}).has_value()); + Void::Testing::expect( + decode(valid, TextLimits{.max_output = 5}).has_value()); + + Void::Testing::expect( + !decode_crockford("MZXW6YTB", TextLimits{.max_input = 7}).has_value()); + Void::Testing::expect( + !decode_crockford("MZXW6YTB", TextLimits{.max_output = 4}).has_value()); +}