Skip to content

Commit 36b85a1

Browse files
committed
fix(util): avoid sign extension in base64 encodesr
1 parent 6031cdd commit 36b85a1

File tree

2 files changed

+23
-7
lines changed

2 files changed

+23
-7
lines changed

util/include/prometheus/detail/base64.h

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,9 @@ inline std::string base64_encode(const std::string& input) {
3737
auto it = input.begin();
3838

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

4949
switch (input.size() % 3) {
5050
case 1:
51-
temp = (*it++) << 16;
51+
temp = static_cast<std::uint8_t>(*it++) << 16;
5252
encoded.append(1, kEncodeLookup[(temp & 0x00FC0000) >> 18]);
5353
encoded.append(1, kEncodeLookup[(temp & 0x0003F000) >> 12]);
5454
encoded.append(2, kPadCharacter);
5555
break;
5656
case 2:
57-
temp = (*it++) << 16;
58-
temp += (*it++) << 8;
57+
temp = static_cast<std::uint8_t>(*it++) << 16;
58+
temp += static_cast<std::uint8_t>(*it++) << 8;
5959
encoded.append(1, kEncodeLookup[(temp & 0x00FC0000) >> 18]);
6060
encoded.append(1, kEncodeLookup[(temp & 0x0003F000) >> 12]);
6161
encoded.append(1, kEncodeLookup[(temp & 0x00000FC0) >> 6]);
@@ -118,7 +118,7 @@ inline std::string base64_decode(const std::string& input) {
118118

119119
decoded.push_back((temp >> 16) & 0x000000FF);
120120
decoded.push_back((temp >> 8) & 0x000000FF);
121-
decoded.push_back((temp)&0x000000FF);
121+
decoded.push_back((temp) & 0x000000FF);
122122
}
123123

124124
return decoded;

util/tests/unit/base64_test.cc

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,29 @@ struct TestVector {
1313
};
1414

1515
const TestVector testVector[] = {
16+
// RFC 3548 examples
17+
{"\x14\xfb\x9c\x03\xd9\x7e", "FPucA9l+"},
18+
{"\x14\xfb\x9c\x03\xd9", "FPucA9k="},
19+
{"\x14\xfb\x9c\x03", "FPucAw=="},
20+
21+
// RFC 4648 examples
1622
{"", ""},
1723
{"f", "Zg=="},
1824
{"fo", "Zm8="},
1925
{"foo", "Zm9v"},
2026
{"foob", "Zm9vYg=="},
2127
{"fooba", "Zm9vYmE="},
2228
{"foobar", "Zm9vYmFy"},
29+
30+
// Wikipedia examples
31+
{"sure.", "c3VyZS4="},
32+
{"sure", "c3VyZQ=="},
33+
{"sur", "c3Vy"},
34+
{"su", "c3U="},
35+
{"leasure.", "bGVhc3VyZS4="},
36+
{"easure.", "ZWFzdXJlLg=="},
37+
{"asure.", "YXN1cmUu"},
38+
{"sure.", "c3VyZS4="},
2339
};
2440

2541
using namespace testing;

0 commit comments

Comments
 (0)