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 "secrets/secrets.h"
0006 
0007 #include "test-utils/random.h"
0008 
0009 #include <QTest>
0010 #include <QtDebug>
0011 
0012 class KeyDerivationTest: public QObject
0013 {
0014     Q_OBJECT
0015 private Q_SLOTS:
0016     void testRecovery(void);
0017 };
0018 
0019 void KeyDerivationTest::testRecovery(void)
0020 {
0021     QScopedPointer<secrets::SecureMemory> passwd(secrets::SecureMemory::allocate(13ULL));
0022     QVERIFY2(passwd, "password memory should be allocated");
0023     memcpy(passwd->data(), "Hello, world!", passwd->size());
0024 
0025     std::optional<secrets::KeyDerivationParameters> defaults = secrets::KeyDerivationParameters::create();
0026     QVERIFY2(defaults, "defaults should yield a valid key parameters object");
0027 
0028     QScopedPointer<secrets::SecureMasterKey> origMasterKey(secrets::SecureMasterKey::derive(passwd.data(), *defaults, &test::fakeRandom));
0029     QVERIFY2(origMasterKey, "key derivation should succeed");
0030 
0031     QByteArray expectedSalt(crypto_pwhash_SALTBYTES, 'A');
0032     QCOMPARE(origMasterKey->salt(), expectedSalt);
0033 
0034     QScopedPointer<secrets::SecureMasterKey> copyKey(secrets::SecureMasterKey::derive(passwd.data(), *defaults, expectedSalt, &test::fakeRandom));
0035     QVERIFY2(copyKey, "recovering/re-deriving a copy of the master key should succeed");
0036 
0037     QScopedPointer<secrets::SecureMemory> payload(secrets::SecureMemory::allocate(42ULL));
0038     QVERIFY2(payload, "allocating the secure memory input buffer should succeed");
0039 
0040     memset(payload->data(), 'B', 42ULL);
0041 
0042     std::optional<secrets::EncryptedSecret> fromOrigKey = origMasterKey->encrypt(payload.data());
0043     QVERIFY2(fromOrigKey, "encryption of the payload should succeed with the original master key");
0044 
0045     std::optional<secrets::EncryptedSecret> fromCopyKey = copyKey->encrypt(payload.data());
0046     QVERIFY2(fromCopyKey, "encryption of the payload should also succeed with the recovered copy of the master key");
0047 
0048     QCOMPARE(fromOrigKey->cryptText(), fromCopyKey->cryptText());
0049     QCOMPARE(fromOrigKey->nonce(), fromCopyKey->nonce());
0050 }
0051 
0052 QTEST_APPLESS_MAIN(KeyDerivationTest)
0053 
0054 #include "key-derivation.moc"