[Base64] Add validation

This commit is contained in:
TennesseeTrash 2025-06-09 01:42:12 +02:00
parent 67d28c276b
commit dd75c91403
2 changed files with 38 additions and 0 deletions

View file

@ -138,6 +138,33 @@ namespace Garbage::Base64
return result;
}
[[nodiscard]] constexpr
bool Validate(std::string_view data)
{
// Technically superfluous - the decoder can deal with unpadded data.
if (data.size() % 4 != 0) {
return false;
}
std::size_t i = 0;
for (char ch : data) {
bool condition = (ch == '+') ||
(ch >= '/' && ch <= '9') ||
(ch >= 'A' && ch <= 'Z') ||
(ch >= 'a' && ch <= 'z');
if (!condition) {
// Allow '=' for the last two character
if (i >= data.size() - 2 && ch == '=') {
continue;
}
return false;
}
++i;
}
return true;
}
}
#endif // GARBAGE_BASE64_HPP

View file

@ -10,6 +10,8 @@ TEST_CASE("Base64 encoding/decoding tests")
std::string encoded = Garbage::Base64::Encode(data);
REQUIRE(encoded.size() == 0);
REQUIRE(Garbage::Base64::Validate(encoded));
std::vector<std::uint8_t> decoded = Garbage::Base64::Decode(encoded);
REQUIRE(encoded.size() == 0);
}
@ -21,12 +23,15 @@ TEST_CASE("Base64 encoding/decoding tests")
std::string encoded = Garbage::Base64::Encode(data);
REQUIRE(encoded == "TWFueSBoYW5kcyBtYWtlIGxpZ2h0IHdvcmsu");
REQUIRE(Garbage::Base64::Validate(encoded));
}
SECTION("Decoding short data")
{
std::string data("TWFueSBoYW5kcyBtYWtlIGxpZ2h0IHdvcmsu");
REQUIRE(Garbage::Base64::Validate(data));
std::vector<std::uint8_t> decoded = Garbage::Base64::Decode(data);
std::string destination(decoded.begin(), decoded.end());
REQUIRE(destination == "Many hands make light work.");
@ -39,12 +44,15 @@ TEST_CASE("Base64 encoding/decoding tests")
std::string encoded = Garbage::Base64::Encode(data);
REQUIRE(encoded == "V2l0aCBhIHBhZGRpbmc=");
REQUIRE(Garbage::Base64::Validate(encoded));
}
SECTION("Decoding with a padding char")
{
std::string data("V2l0aCBhIHBhZGRpbmc=");
REQUIRE(Garbage::Base64::Validate(data));
std::vector<std::uint8_t> decoded = Garbage::Base64::Decode(data);
std::string destination(decoded.begin(), decoded.end());
REQUIRE(destination == "With a padding");
@ -57,12 +65,15 @@ TEST_CASE("Base64 encoding/decoding tests")
std::string encoded = Garbage::Base64::Encode(data);
REQUIRE(encoded == "V2l0aCB0d28gcGFkZGluZw==");
REQUIRE(Garbage::Base64::Validate(encoded));
}
SECTION("Decoding with two padding chars")
{
std::string data("V2l0aCB0d28gcGFkZGluZw==");
REQUIRE(Garbage::Base64::Validate(data));
std::vector<std::uint8_t> decoded = Garbage::Base64::Decode(data);
std::string destination(decoded.begin(), decoded.end());
REQUIRE(destination == "With two padding");