From b83e825fab16f83f86149ead78efb6ec3d2fa16d Mon Sep 17 00:00:00 2001 From: Ahmad Samir Date: Thu, 26 Dec 2024 15:11:30 +0200 Subject: [PATCH] QCryptographicHash: hashInto(): check the buffer size earlier We can use hashLengthInternal() to check if the buffer is big enough. This matches what the QCH::hash() method does, it also has an assert that `result.size() == ba.size()`, so we can assume this works with OpenSSL's EVP_MD_get_size() in EVP::finalizeUnchecked(). Amends c70c81b371993ca865d523bb5f37eac4eb8a972b. Pick-to: 6.9 6.8 Change-Id: I64935f3d590ab243b361a0b764f011c388820e32 Reviewed-by: Marc Mutz --- src/corelib/tools/qcryptographichash.cpp | 6 ++++-- .../tools/qcryptographichash/tst_qcryptographichash.cpp | 3 +++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/corelib/tools/qcryptographichash.cpp b/src/corelib/tools/qcryptographichash.cpp index 0e677ceea36..0a4f2351088 100644 --- a/src/corelib/tools/qcryptographichash.cpp +++ b/src/corelib/tools/qcryptographichash.cpp @@ -1128,13 +1128,15 @@ QByteArrayView QCryptographicHash::hashInto(QSpan buffer, QSpan data, Algorithm method) noexcept { + if (buffer.size() < hashLengthInternal(method)) + return {}; // buffer too small + QCryptographicHashPrivate hash(method); for (QByteArrayView part : data) hash.addData(part); hash.finalizeUnchecked(); // no mutex needed: no-one but us has access to 'hash' auto result = hash.resultView(); - if (buffer.size() < result.size()) - return {}; // buffer too small + Q_ASSERT(buffer.size() >= result.size()); // ### optimize: have the method directly write into `buffer` memcpy(buffer.data(), result.data(), result.size()); return buffer.first(result.size()); diff --git a/tests/auto/corelib/tools/qcryptographichash/tst_qcryptographichash.cpp b/tests/auto/corelib/tools/qcryptographichash/tst_qcryptographichash.cpp index 60a0d2dcf09..f57e2812d10 100644 --- a/tests/auto/corelib/tools/qcryptographichash/tst_qcryptographichash.cpp +++ b/tests/auto/corelib/tools/qcryptographichash/tst_qcryptographichash.cpp @@ -206,6 +206,9 @@ void tst_QCryptographicHash::static_hash() std::byte buffer[1024]; QCOMPARE(QCryptographicHash::hashInto(buffer, first, _algo), hash_first); + + // Too small buffer + QVERIFY(QCryptographicHash::hashInto(QSpan{buffer}.first(5), first, _algo).isNull()); }