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 <marc.mutz@qt.io>
This commit is contained in:
Ahmad Samir 2024-12-26 15:11:30 +02:00 committed by Marc Mutz
parent cfa7d41db0
commit b83e825fab
2 changed files with 7 additions and 2 deletions

View File

@ -1128,13 +1128,15 @@ QByteArrayView QCryptographicHash::hashInto(QSpan<std::byte> buffer,
QSpan<const QByteArrayView> 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());

View File

@ -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());
}