File indexing completed on 2024-04-28 05:50:04

0001 /*
0002  * SPDX-License-Identifier: GPL-3.0-or-later
0003  * SPDX-FileCopyrightText: 2020 Johan Ouwerkerk <jm.ouwerkerk@gmail.com>
0004  */
0005 #include "hmac/hmac.h"
0006 
0007 #include <QMessageAuthenticationCode>
0008 #include <QTest>
0009 #include <QtDebug>
0010 
0011 class HMacSamplesTest: public QObject
0012 {
0013     Q_OBJECT
0014 private Q_SLOTS:
0015     void testAgainstQMessageAuthenticationCode(void);
0016     void testAgainstQMessageAuthenticationCode_data(void);
0017 };
0018 
0019 static const QByteArray helloWorldKey("hello, world!");
0020 static const QByteArray helloWorldMessage("Hello, world!");
0021 
0022 static const QByteArray longerThanMaxBlockSizeKey(
0023     "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. "
0024     "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. "
0025     "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. "
0026     "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
0027 );
0028 
0029 static void define_test_data(void)
0030 {
0031     QTest::addColumn<int>("hash");
0032     QTest::addColumn<QByteArray>("key");
0033     QTest::addColumn<QByteArray>("message");
0034     QTest::addColumn<QByteArray>("mac");
0035 }
0036 
0037 static void define_test_case(const char *testCase, QCryptographicHash::Algorithm hash, const QByteArray &key, const QByteArray &message)
0038 {
0039     QMessageAuthenticationCode referenceImpl(hash, key);
0040     referenceImpl.addData(message);
0041     QByteArray expected = referenceImpl.result().toHex();
0042 
0043     QTest::newRow(qPrintable(QLatin1String(testCase))) << ((int) hash) << key << message << expected;
0044 }
0045 
0046 void HMacSamplesTest::testAgainstQMessageAuthenticationCode(void)
0047 {
0048     QFETCH(int, hash);
0049     QFETCH(QByteArray, key);
0050     QFETCH(QByteArray, message);
0051 
0052     QByteArray scratchKey(key);
0053     const std::optional<QByteArray> result = hmac::compute((QCryptographicHash::Algorithm) hash, scratchKey.data(), scratchKey.size(), message, false);
0054     QVERIFY2(result, "mac should be computed successfully");
0055     QTEST(result->toHex(), "mac");
0056 }
0057 
0058 void HMacSamplesTest::testAgainstQMessageAuthenticationCode_data(void)
0059 {
0060     define_test_data();
0061 
0062     define_test_case("'hello, world' in HMAC-SHA1", QCryptographicHash::Sha1, helloWorldKey, helloWorldMessage); // ce9935b62371cc0cb2c31b016af3fe78a5a9c9c6
0063     define_test_case("long key in HMAC-SH1", QCryptographicHash::Sha1, longerThanMaxBlockSizeKey, helloWorldMessage); // 1ed7533a4f28ab52729a4a102edae6d0b7b6a049
0064 }
0065 
0066 QTEST_APPLESS_MAIN(HMacSamplesTest)
0067 
0068 #include "hmac-samples.moc"