QCryptographicHash: Add a static method to retrieve hash length

It's useful when you need to check how long a hash will be without first
generating one.

[ChangeLog][QtCore][QCryptographicHash] Add a static method, hashLength,
which returns the length of the output of a hash function in bytes.

Change-Id: Id6a454016523de83d157fd95c50105c6db4bb1d9
Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
Reviewed-by: Edward Welbourne <edward.welbourne@qt.io>
This commit is contained in:
Mårten Nordheim 2018-04-03 12:40:53 +02:00
parent e027c7241f
commit 5e7a64d1e3
3 changed files with 52 additions and 0 deletions

View File

@ -544,6 +544,46 @@ QByteArray QCryptographicHash::hash(const QByteArray &data, Algorithm method)
return hash.result();
}
/*!
Returns the size of the output of the selected hash \a method in bytes.
\since 5.12
*/
int QCryptographicHash::hashLength(QCryptographicHash::Algorithm method)
{
switch (method) {
case QCryptographicHash::Sha1:
return 20;
#ifndef QT_CRYPTOGRAPHICHASH_ONLY_SHA1
case QCryptographicHash::Md4:
return 16;
case QCryptographicHash::Md5:
return 16;
case QCryptographicHash::Sha224:
return SHA224HashSize;
case QCryptographicHash::Sha256:
return SHA256HashSize;
case QCryptographicHash::Sha384:
return SHA384HashSize;
case QCryptographicHash::Sha512:
return SHA512HashSize;
case QCryptographicHash::RealSha3_224:
case QCryptographicHash::Keccak_224:
return 224 / 8;
case QCryptographicHash::RealSha3_256:
case QCryptographicHash::Keccak_256:
return 256 / 8;
case QCryptographicHash::RealSha3_384:
case QCryptographicHash::Keccak_384:
return 384 / 8;
case QCryptographicHash::RealSha3_512:
case QCryptographicHash::Keccak_512:
return 512 / 8;
#endif
}
return 0;
}
QT_END_NAMESPACE
#ifndef QT_NO_QOBJECT

View File

@ -101,6 +101,7 @@ public:
QByteArray result() const;
static QByteArray hash(const QByteArray &data, Algorithm method);
static int hashLength(Algorithm method);
private:
Q_DISABLE_COPY(QCryptographicHash)
QCryptographicHashPrivate *d;

View File

@ -29,6 +29,7 @@
#include <QtCore/QCoreApplication>
#include <QtTest/QtTest>
#include <QtCore/QMetaEnum>
Q_DECLARE_METATYPE(QCryptographicHash::Algorithm)
@ -45,6 +46,7 @@ private slots:
void sha3();
void files_data();
void files();
void hashLength();
};
void tst_QCryptographicHash::repeated_result_data()
@ -291,6 +293,15 @@ void tst_QCryptographicHash::files()
}
}
void tst_QCryptographicHash::hashLength()
{
auto metaEnum = QMetaEnum::fromType<QCryptographicHash::Algorithm>();
for (int i = 0, value = metaEnum.value(i); value != -1; value = metaEnum.value(++i)) {
auto algorithm = QCryptographicHash::Algorithm(value);
QByteArray output = QCryptographicHash::hash(QByteArrayLiteral("test"), algorithm);
QCOMPARE(QCryptographicHash::hashLength(algorithm), output.length());
}
}
QTEST_MAIN(tst_QCryptographicHash)
#include "tst_qcryptographichash.moc"