From 10f13938bbf1474451fadcd62e1c31c4b5f5b3d7 Mon Sep 17 00:00:00 2001 From: David Kalnischkies Date: Thu, 3 Dec 2020 10:41:43 +0100 Subject: Fix incorrect base64 encoding due to int promotion For \xff and friends with the highest bit set and hence being a negative value on signed char systems the wrong encoding is produced as we run into undefined behaviour accessing negative array indexes. We can avoid this problem simply by using an unsigned data type. --- apt-pkg/contrib/strutl.cc | 2 +- test/libapt/strutil_test.cc | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/apt-pkg/contrib/strutl.cc b/apt-pkg/contrib/strutl.cc index bd4856526..826b21478 100644 --- a/apt-pkg/contrib/strutl.cc +++ b/apt-pkg/contrib/strutl.cc @@ -597,7 +597,7 @@ string Base64Encode(const string &S) base64. */ for (string::const_iterator I = S.begin(); I < S.end(); I += 3) { - char Bits[3] = {0,0,0}; + uint8_t Bits[3] = {0,0,0}; Bits[0] = I[0]; if (I + 1 < S.end()) Bits[1] = I[1]; diff --git a/test/libapt/strutil_test.cc b/test/libapt/strutil_test.cc index 349946b5f..f101d72cf 100644 --- a/test/libapt/strutil_test.cc +++ b/test/libapt/strutil_test.cc @@ -167,6 +167,10 @@ TEST(StrUtilTest,Base64Encode) EXPECT_EQ("ZS4=", Base64Encode("e.")); EXPECT_EQ("Lg==", Base64Encode(".")); EXPECT_EQ("", Base64Encode("")); + EXPECT_EQ("IA==", Base64Encode("\x20")); + EXPECT_EQ("/w==", Base64Encode("\xff")); + EXPECT_EQ("/A==", Base64Encode("\xfc")); + EXPECT_EQ("//8=", Base64Encode("\xff\xff")); } static void ReadMessagesTestWithNewLine(char const * const nl, char const * const ab) { -- cgit v1.2.3-18-g5258