aboutsummaryrefslogtreecommitdiff
path: root/src/Hash.cpp
diff options
context:
space:
mode:
authorAleksi Lindeman <0xdec05eba@gmail.com>2018-03-05 22:45:56 +0100
committerAleksi Lindeman <0xdec05eba@gmail.com>2018-03-05 22:48:26 +0100
commit2ffb47d0043e57707474e5ae811f97c2e5e93f25 (patch)
treefd60b300cdf736de5adc68b395105dcfc6a43f09 /src/Hash.cpp
parent66661e47dc826f50b690e080057f47a0ea27016c (diff)
Implement 'create' operation, add seeding
Seeding is currently only done on the key you specify, in the future the user should request data that it can seed.
Diffstat (limited to 'src/Hash.cpp')
-rw-r--r--src/Hash.cpp55
1 files changed, 55 insertions, 0 deletions
diff --git a/src/Hash.cpp b/src/Hash.cpp
new file mode 100644
index 0000000..5d2f914
--- /dev/null
+++ b/src/Hash.cpp
@@ -0,0 +1,55 @@
+#include "../include/Hash.hpp"
+#include "../include/bin2hex.hpp"
+#include <sodium/crypto_generichash_blake2b.h>
+#include <sodium/core.h>
+#include <cstring>
+
+namespace odhtdb
+{
+ struct SodiumInitializer
+ {
+ SodiumInitializer()
+ {
+ if(sodium_init() < 0)
+ throw std::runtime_error("Failed to initialize libsodium");
+ }
+ };
+
+ static SodiumInitializer __sodiumInitializer;
+
+ // Source: https://stackoverflow.com/a/11414104 (public license)
+ static size_t fnvHash(const unsigned char *key, int len)
+ {
+ size_t h = 2166136261;
+ for (int i = 0; i < len; i++)
+ h = (h * 16777619) ^ key[i];
+ return h;
+ }
+
+ Hash::Hash()
+ {
+ memset(data, 0, HASH_BYTE_SIZE);
+ }
+
+ Hash::Hash(const void *input, const size_t inputSize)
+ {
+ int result = crypto_generichash_blake2b((unsigned char*)data, HASH_BYTE_SIZE, (const unsigned char*)input, inputSize, nullptr, 0);
+ if(result < 0)
+ throw HashException("Failed to hash data using blake2b");
+ }
+
+ size_t Hash::operator()() const
+ {
+ return fnvHash((const unsigned char*)data, HASH_BYTE_SIZE);
+ }
+
+ bool Hash::operator==(const Hash &other) const
+ {
+ return memcmp(data, other.data, HASH_BYTE_SIZE) == 0;
+ }
+
+ std::string Hash::toString() const
+ {
+ return bin2hex(data, HASH_BYTE_SIZE);
+ }
+}