From 87dc080bbfe945e6e505d77f6a14fe4f448191fa Mon Sep 17 00:00:00 2001 From: Adrien Beraud Date: Thu, 2 Nov 2017 14:25:46 -0400 Subject: [PATCH] crypto: add raw hash function --- include/opendht/crypto.h | 2 ++ src/crypto.cpp | 15 ++++++++++++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/include/opendht/crypto.h b/include/opendht/crypto.h index 71648288..a840576b 100644 --- a/include/opendht/crypto.h +++ b/include/opendht/crypto.h @@ -601,6 +601,8 @@ OPENDHT_PUBLIC Identity generateEcIdentity(const std::string& name = "dhtnode", */ OPENDHT_PUBLIC Blob hash(const Blob& data, size_t hash_length = 512/8); +OPENDHT_PUBLIC void hash(const uint8_t* data, size_t data_length, uint8_t* hash, size_t hash_length); + /** * Generates an encryption key from a text password, * making the key longer to bruteforce. diff --git a/src/crypto.cpp b/src/crypto.cpp index 6c029d56..8e7d2a2c 100644 --- a/src/crypto.cpp +++ b/src/crypto.cpp @@ -84,7 +84,7 @@ static constexpr size_t PASSWORD_SALT_LENGTH {16}; constexpr gnutls_digest_algorithm_t gnutlsHashAlgo(size_t min_res) { return (min_res > 256/8) ? GNUTLS_DIG_SHA512 : ( - (min_res > 128/8) ? GNUTLS_DIG_SHA256 : ( + (min_res > 160/8) ? GNUTLS_DIG_SHA256 : ( GNUTLS_DIG_SHA1)); } @@ -212,12 +212,21 @@ Blob hash(const Blob& data, size_t hash_len) Blob res; res.resize(res_size); const gnutls_datum_t gdat {(uint8_t*)data.data(), (unsigned)data.size()}; - if (gnutls_fingerprint(algo, &gdat, res.data(), &res_size)) - throw CryptoException("Can't compute hash !"); + if (auto err = gnutls_fingerprint(algo, &gdat, res.data(), &res_size)) + throw CryptoException(std::string("Can't compute hash: ") + gnutls_strerror(err)); res.resize(std::min(hash_len, res_size)); return res; } +void hash(const uint8_t* data, size_t data_length, uint8_t* hash, size_t hash_length) +{ + auto algo = gnutlsHashAlgo(hash_length); + size_t res_size = hash_length; + const gnutls_datum_t gdat {(uint8_t*)data, (unsigned)data_length}; + if (auto err = gnutls_fingerprint(algo, &gdat, hash, &res_size)) + throw CryptoException(std::string("Can't compute hash: ") + gnutls_strerror(err)); +} + PrivateKey::PrivateKey() {}