2
* Copyright (C) 2021 KeePassXC Team <team@keepassxc.org>
3
* Copyright (C) 2010 Felix Geyer <debfx@fobos.de>
5
* This program is free software: you can redistribute it and/or modify
6
* it under the terms of the GNU General Public License as published by
7
* the Free Software Foundation, either version 2 or (at your option)
8
* version 3 of the License.
10
* This program is distributed in the hope that it will be useful,
11
* but WITHOUT ANY WARRANTY; without even the implied warranty of
12
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
* GNU General Public License for more details.
15
* You should have received a copy of the GNU General Public License
16
* along with this program. If not, see <http://www.gnu.org/licenses/>.
19
#include "CryptoHash.h"
21
#include <QScopedPointer>
23
#include <botan/hash.h>
26
class CryptoHashPrivate
29
QScopedPointer<Botan::HashFunction> hashFunction;
30
QScopedPointer<Botan::MessageAuthenticationCode> hmacFunction;
33
CryptoHash::CryptoHash(Algorithm algo, bool hmac)
34
: d_ptr(new CryptoHashPrivate())
39
case CryptoHash::Sha256:
41
d->hmacFunction.reset(Botan::MessageAuthenticationCode::create("HMAC(SHA-256)").release());
43
d->hashFunction.reset(Botan::HashFunction::create("SHA-256").release());
46
case CryptoHash::Sha512:
48
d->hmacFunction.reset(Botan::MessageAuthenticationCode::create("HMAC(SHA-512)").release());
50
d->hashFunction.reset(Botan::HashFunction::create("SHA-512").release());
59
CryptoHash::~CryptoHash()
65
void CryptoHash::addData(const QByteArray& data)
74
if (d->hmacFunction) {
75
d->hmacFunction->update(reinterpret_cast<const uint8_t*>(data.data()), data.size());
76
} else if (d->hashFunction) {
77
d->hashFunction->update(reinterpret_cast<const uint8_t*>(data.data()), data.size());
79
} catch (std::exception& e) {
80
qWarning("CryptoHash::update failed to add data: %s", e.what());
85
void CryptoHash::setKey(const QByteArray& data)
89
if (d->hmacFunction) {
91
d->hmacFunction->set_key(reinterpret_cast<const uint8_t*>(data.data()), data.size());
92
} catch (std::exception& e) {
93
qWarning("CryptoHash::setKey failed to set HMAC key: %s", e.what());
99
QByteArray CryptoHash::result() const
101
Q_D(const CryptoHash);
103
Botan::secure_vector<uint8_t> result;
104
if (d->hmacFunction) {
105
result = d->hmacFunction->final();
106
} else if (d->hashFunction) {
107
result = d->hashFunction->final();
109
return {reinterpret_cast<const char*>(result.data()), int(result.size())};
112
QByteArray CryptoHash::hash(const QByteArray& data, Algorithm algo)
114
CryptoHash cryptoHash(algo);
115
cryptoHash.addData(data);
116
return cryptoHash.result();
119
QByteArray CryptoHash::hmac(const QByteArray& data, const QByteArray& key, Algorithm algo)
121
CryptoHash cryptoHash(algo, true);
122
cryptoHash.setKey(key);
123
cryptoHash.addData(data);
124
return cryptoHash.result();