diff options
Diffstat (limited to 'src/crypto/CryptoHash.cpp')
-rw-r--r-- | src/crypto/CryptoHash.cpp | 47 |
1 files changed, 40 insertions, 7 deletions
diff --git a/src/crypto/CryptoHash.cpp b/src/crypto/CryptoHash.cpp index d116451fc..12c6bf791 100644 --- a/src/crypto/CryptoHash.cpp +++ b/src/crypto/CryptoHash.cpp @@ -28,28 +28,40 @@ public: int hashLen; }; -CryptoHash::CryptoHash(CryptoHash::Algorithm algo) +CryptoHash::CryptoHash(Algorithm algo, bool hmac) : d_ptr(new CryptoHashPrivate()) { Q_D(CryptoHash); Q_ASSERT(Crypto::initalized()); - int algoGcrypt; + int algoGcrypt = -1; + unsigned int flagsGcrypt = GCRY_MD_FLAG_SECURE; switch (algo) { case CryptoHash::Sha256: algoGcrypt = GCRY_MD_SHA256; break; + case CryptoHash::Sha512: + algoGcrypt = GCRY_MD_SHA512; + break; + default: Q_ASSERT(false); break; } - gcry_error_t error = gcry_md_open(&d->ctx, algoGcrypt, 0); + if (hmac) { + flagsGcrypt |= GCRY_MD_FLAG_HMAC; + } + + gcry_error_t error = gcry_md_open(&d->ctx, algoGcrypt, flagsGcrypt); + if (error != GPG_ERR_NO_ERROR) { + qWarning("Gcrypt error (ctor): %s", gcry_strerror(error)); + qWarning("Gcrypt error (ctor): %s", gcry_strsource(error)); + } Q_ASSERT(error == 0); // TODO: error handling - Q_UNUSED(error); d->hashLen = gcry_md_get_algo_dlen(algoGcrypt); } @@ -71,7 +83,19 @@ void CryptoHash::addData(const QByteArray& data) return; } - gcry_md_write(d->ctx, data.constData(), data.size()); + gcry_md_write(d->ctx, data.constData(), static_cast<size_t>(data.size())); +} + +void CryptoHash::setKey(const QByteArray& data) +{ + Q_D(CryptoHash); + + gcry_error_t error = gcry_md_setkey(d->ctx, data.constData(), static_cast<size_t>(data.size())); + if (error) { + qWarning("Gcrypt error (setKey): %s", gcry_strerror(error)); + qWarning("Gcrypt error (setKey): %s", gcry_strsource(error)); + } + Q_ASSERT(error == 0); } void CryptoHash::reset() @@ -85,14 +109,23 @@ QByteArray CryptoHash::result() const { Q_D(const CryptoHash); - const char* result = reinterpret_cast<const char*>(gcry_md_read(d->ctx, 0)); + const auto result = reinterpret_cast<const char*>(gcry_md_read(d->ctx, 0)); return QByteArray(result, d->hashLen); } -QByteArray CryptoHash::hash(const QByteArray& data, CryptoHash::Algorithm algo) +QByteArray CryptoHash::hash(const QByteArray& data, Algorithm algo) { // replace with gcry_md_hash_buffer()? CryptoHash cryptoHash(algo); cryptoHash.addData(data); return cryptoHash.result(); } + +QByteArray CryptoHash::hmac(const QByteArray& data, const QByteArray& key, Algorithm algo) +{ + // replace with gcry_md_hash_buffer()? + CryptoHash cryptoHash(algo, true); + cryptoHash.setKey(key); + cryptoHash.addData(data); + return cryptoHash.result(); +} |