diff --git a/tdutils/td/utils/base64.cpp b/tdutils/td/utils/base64.cpp index e549869bb..2408826dc 100644 --- a/tdutils/td/utils/base64.cpp +++ b/tdutils/td/utils/base64.cpp @@ -121,7 +121,7 @@ Result base64_decode(Slice base64) { TRY_RESULT_ASSIGN(base64, base64_drop_padding(base64)); string output; - output.reserve(((base64.size() + 3) >> 2) * 3); + output.reserve((base64.size() >> 2) * 3 + (((base64.size() & 3) + 1) >> 1)); TRY_STATUS(base64_do_decode(base64, [&output](char c) { output += c; })); return output; } @@ -129,14 +129,10 @@ Result base64_decode(Slice base64) { Result base64_decode_secure(Slice base64) { TRY_RESULT_ASSIGN(base64, base64_drop_padding(base64)); - SecureString output(((base64.size() + 3) >> 2) * 3); + SecureString output((base64.size() >> 2) * 3 + (((base64.size() & 3) + 1) >> 1)); char *ptr = output.as_mutable_slice().begin(); TRY_STATUS(base64_do_decode(base64, [&ptr](char c) { *ptr++ = c; })); - size_t size = ptr - output.as_mutable_slice().begin(); - if (size == output.size()) { - return std::move(output); - } - return SecureString(output.as_slice().substr(0, size)); + return std::move(output); } string base64_encode(Slice input) { @@ -151,7 +147,7 @@ Result base64url_decode(Slice base64) { TRY_RESULT_ASSIGN(base64, base64_drop_padding(base64)); string output; - output.reserve(((base64.size() + 3) >> 2) * 3); + output.reserve((base64.size() >> 2) * 3 + (((base64.size() & 3) + 1) >> 1)); TRY_STATUS(base64_do_decode(base64, [&output](char c) { output += c; })); return output; } diff --git a/tdutils/test/misc.cpp b/tdutils/test/misc.cpp index 8cf133530..c288b15a6 100644 --- a/tdutils/test/misc.cpp +++ b/tdutils/test/misc.cpp @@ -223,6 +223,10 @@ TEST(Misc, base64) { decoded = base64_decode(encoded); ASSERT_TRUE(decoded.is_ok()); ASSERT_TRUE(decoded.ok() == s); + + auto decoded_secure = base64_decode_secure(encoded); + ASSERT_TRUE(decoded_secure.is_ok()); + ASSERT_TRUE(decoded_secure.ok().as_slice() == s); } }