浏览代码

fix base64 decoding

Kolja Strohm 2 年之前
父节点
当前提交
e50fc87bc1
共有 3 个文件被更改,包括 14 次插入4 次删除
  1. 3 4
      Base64.cpp
  2. 11 0
      Framework Tests/Base64.cpp
  3. 二进制
      Framework Tests/Framwork.dll

+ 3 - 4
Base64.cpp

@@ -1,5 +1,4 @@
 #include "Base64.h"
-#include <math.h>
 
 using namespace Framework;
 
@@ -63,7 +62,7 @@ bool Framework::base64Decode(Text base64, char** data, int* length)
 			return false;
 		l++;
 	}
-	*length = (int)ceil(l / 4.f) * 3;
+	*length = (l * 3) / 4;
 	*data = new char[*length + 1];
 	while (base64[k])
 	{
@@ -75,7 +74,7 @@ bool Framework::base64Decode(Text base64, char** data, int* length)
 			char_array_3[0] = (unsigned char)((char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4));
 			char_array_3[1] = (unsigned char)(((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2));
 			char_array_3[2] = (unsigned char)(((char_array_4[2] & 0x3) << 6) + char_array_4[3]);
-			for (i = 0; (i < 3); i++)
+			for (i = 0; (i < 3) && n < *length; i++)
 				(*data)[n++] = char_array_3[i];
 			i = 0;
 		}
@@ -90,7 +89,7 @@ bool Framework::base64Decode(Text base64, char** data, int* length)
 		char_array_3[0] = (unsigned char)((char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4));
 		char_array_3[1] = (unsigned char)(((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2));
 		char_array_3[2] = (unsigned char)(((char_array_4[2] & 0x3) << 6) + char_array_4[3]);
-		for (j = 0; (j < i - 1); j++)
+		for (j = 0; (j < i - 1) && n < *length; j++)
 			(*data)[n++] = char_array_3[j];
 	}
 	(*data)[*length] = '\0';

+ 11 - 0
Framework Tests/Base64.cpp

@@ -40,5 +40,16 @@ namespace FrameworkTests
 			Assert::AreEqual(0, decodecLength);
 			delete[] decodedData;
 		}
+
+		TEST_METHOD(TestDecodeAndEncode)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jln02TspaXoMEkOLdzJfHFTs1cNeencBgBVAwB6AABoo4lsQ5OkqWgKlg6vfz73jGrVV+ZHqZqethSIlBoEAAAAAPy8jWn+IQ6piBdBlsW/075NP5SkJtpOv3oGANMEAAAAAJntB5erkwGrtA5VPiWV0+pWqKmj5j5IDRqWzJScoZc3kJ3NPDLN5uXbPSQB0vfrKqCVzYjTF5XtrWOCSgUAAAAAGoGUt0/Q6B64z/j18vnI6uXyjHzAFVHXqj+FDsHPEttRppOgeH29MU23J0Gy7yyZ47gWpc1mfXilAwAAAACFZ9KXQyQ/1sO2VYLnojoQ4uv+EIXjx5uJlQMAAAAAMAQAAAAABw+oCpMR2yxU/morwyKARgojgBkGAGwZFvH73Y6FdJGMgjqVF0pyQp1yrMg2zUp812z78HJpC4dcB2bpjNl8Gly1r3IBIrSek2FnyDCwRgkeQviPqwQAAAAAkAQAAAAAGAgAAAAAC33xl1dusLMkYA==";
+			char* decodedData = 0;
+			int decodecLength;
+			Framework::base64Decode(data, &decodedData, &decodecLength);
+			Framework::Text encoded = Framework::base64Encode(decodedData, decodecLength);
+			Assert::IsTrue(encoded.istGleich(data));
+			delete[] decodedData;
+		}
 	};
 }

二进制
Framework Tests/Framwork.dll