1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
#include "../include/odhtdb/Hash.hpp"
#include "../include/odhtdb/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;
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");
}
Hash::Hash(const Hash &other)
{
memmove(data, other.data, HASH_BYTE_SIZE);
}
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);
}
}
|