Skip to content

Commit

Permalink
[Base64Utils] Removed regex to validate base64
Browse files Browse the repository at this point in the history
with very large strings regex can cause this error:
regex_error(error_stack): There was insufficient memory to determine whether the regular expression could match the specified character sequence

seem to be a common c++ library problem that happen when regex pattern
is complex, so has been replaced with similar code implementation
  • Loading branch information
CastagnaIT committed Oct 3, 2024
1 parent bbd8408 commit 28e581c
Showing 1 changed file with 29 additions and 3 deletions.
32 changes: 29 additions & 3 deletions src/utils/Base64Utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ constexpr char PADDING{'='};
constexpr std::string_view CHARACTERS{"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/"};
constexpr std::string_view REGEX("^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$");
// clang-format off
constexpr unsigned char BASE64_TABLE[] = {
255,255,255,255, 255,255,255,255, 255,255,255,255, 255,255,255,255,
Expand Down Expand Up @@ -214,8 +213,35 @@ std::string UTILS::BASE64::DecodeToStr(std::string_view input)

bool UTILS::BASE64::IsValidBase64(const std::string& input)
{
std::regex base64Regex(REGEX.data());
return std::regex_match(input, base64Regex);
// Check for empty input or incorrect length
if (input.empty() || input.size() % 4 != 0)
return false;

// Use a lookup table for faster character checking
bool lookup[256]{};
for (char c : CHARACTERS)
{
lookup[static_cast<unsigned char>(c)] = true;
}

// Iterate over the input string and check each character
size_t paddingSize = 0;
for (size_t i = 0; i < input.size(); ++i)
{
// Padding must be only at the end of string
if (paddingSize > 0 && input[i] != '=')
return false;
else if (input[i] == '=')
paddingSize++;
else if (!lookup[static_cast<unsigned char>(input[i])])
return false; // Invalid character
}

// Max allowed padding chars
if (paddingSize > 2)
return false;

return true;
}

bool UTILS::BASE64::AddPadding(std::string& base64str)
Expand Down

0 comments on commit 28e581c

Please sign in to comment.