Skip to content

Commit

Permalink
fix(util): avoid sign extension in base64 encodesr
Browse files Browse the repository at this point in the history
  • Loading branch information
gjasny committed Dec 19, 2023
1 parent 6031cdd commit 36b85a1
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
14 changes: 7 additions & 7 deletions util/include/prometheus/detail/base64.h
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ inline std::string base64_encode(const std::string& input) {
auto it = input.begin();

for (std::size_t i = 0; i < input.size() / 3; ++i) {
temp = (*it++) << 16;
temp += (*it++) << 8;
temp += (*it++);
temp = static_cast<std::uint8_t>(*it++) << 16;
temp += static_cast<std::uint8_t>(*it++) << 8;
temp += static_cast<std::uint8_t>(*it++);
encoded.append(1, kEncodeLookup[(temp & 0x00FC0000) >> 18]);
encoded.append(1, kEncodeLookup[(temp & 0x0003F000) >> 12]);
encoded.append(1, kEncodeLookup[(temp & 0x00000FC0) >> 6]);
Expand All @@ -48,14 +48,14 @@ inline std::string base64_encode(const std::string& input) {

switch (input.size() % 3) {
case 1:
temp = (*it++) << 16;
temp = static_cast<std::uint8_t>(*it++) << 16;
encoded.append(1, kEncodeLookup[(temp & 0x00FC0000) >> 18]);
encoded.append(1, kEncodeLookup[(temp & 0x0003F000) >> 12]);
encoded.append(2, kPadCharacter);
break;
case 2:
temp = (*it++) << 16;
temp += (*it++) << 8;
temp = static_cast<std::uint8_t>(*it++) << 16;
temp += static_cast<std::uint8_t>(*it++) << 8;
encoded.append(1, kEncodeLookup[(temp & 0x00FC0000) >> 18]);
encoded.append(1, kEncodeLookup[(temp & 0x0003F000) >> 12]);
encoded.append(1, kEncodeLookup[(temp & 0x00000FC0) >> 6]);
Expand Down Expand Up @@ -118,7 +118,7 @@ inline std::string base64_decode(const std::string& input) {

decoded.push_back((temp >> 16) & 0x000000FF);
decoded.push_back((temp >> 8) & 0x000000FF);
decoded.push_back((temp)&0x000000FF);
decoded.push_back((temp) & 0x000000FF);
}

return decoded;
Expand Down
16 changes: 16 additions & 0 deletions util/tests/unit/base64_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,29 @@ struct TestVector {
};

const TestVector testVector[] = {
// RFC 3548 examples
{"\x14\xfb\x9c\x03\xd9\x7e", "FPucA9l+"},
{"\x14\xfb\x9c\x03\xd9", "FPucA9k="},
{"\x14\xfb\x9c\x03", "FPucAw=="},

// RFC 4648 examples
{"", ""},
{"f", "Zg=="},
{"fo", "Zm8="},
{"foo", "Zm9v"},
{"foob", "Zm9vYg=="},
{"fooba", "Zm9vYmE="},
{"foobar", "Zm9vYmFy"},

// Wikipedia examples
{"sure.", "c3VyZS4="},
{"sure", "c3VyZQ=="},
{"sur", "c3Vy"},
{"su", "c3U="},
{"leasure.", "bGVhc3VyZS4="},
{"easure.", "ZWFzdXJlLg=="},
{"asure.", "YXN1cmUu"},
{"sure.", "c3VyZS4="},
};

using namespace testing;
Expand Down

0 comments on commit 36b85a1

Please sign in to comment.