Skip to content

Commit

Permalink
Added Helper Function to Check Validity of Base64 Encoded String
Browse files Browse the repository at this point in the history
  • Loading branch information
emargolis committed Jul 7, 2023
1 parent e3304c0 commit b9bb3f8
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/lib/support/jsontlv/JsonToTlv.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,40 @@ bool isSignedInteger(const std::string & s)
return isUnsignedInteger(s);
}

bool isValidBase64String(const std::string & s)
{
const std::string base64Chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
size_t len = s.length();

// Check if the length is a multiple of 4
if (len == 0 || len % 4 != 0)
{
return false;
}

size_t paddingLen = 0;
if (s[len - 1] == '=')
{
paddingLen++;
if (s[len - 2] == '=')
{
paddingLen++;
}
}

// Check for invalid characters
for (char c : s.substr(0, len - paddingLen - 1))
{
if (base64Chars.find(c) == std::string::npos)
{
return false;
}
}

return true;
}

CHIP_ERROR ParseJsonKey(const std::string & key, TLV::Tag & tag, ElementTypeContext & type, ElementTypeContext & subType)
{
uint64_t tagNumber = 0;
Expand Down Expand Up @@ -257,6 +291,8 @@ CHIP_ERROR EncodeTlvElement(const json & val, TLV::TLVWriter & writer, TLV::Tag
size_t encodedLen = val.get<std::string>().length();
VerifyOrReturnError(CanCastTo<uint16_t>(encodedLen), CHIP_ERROR_INVALID_ARGUMENT);

VerifyOrReturnError(isValidBase64String(val.get<std::string>()), CHIP_ERROR_INVALID_ARGUMENT);

Platform::ScopedMemoryBuffer<uint8_t> byteString;
byteString.Alloc(BASE64_MAX_DECODED_LEN(static_cast<uint16_t>(encodedLen)));
VerifyOrReturnError(byteString.Get() != nullptr, CHIP_ERROR_NO_MEMORY);
Expand Down

0 comments on commit b9bb3f8

Please sign in to comment.