-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbloom_filter.cpp
More file actions
51 lines (43 loc) · 1.37 KB
/
Copy pathbloom_filter.cpp
File metadata and controls
51 lines (43 loc) · 1.37 KB
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 "bloom_filter.hpp"
#include <openssl/sha.h>
#include <cmath>
#include <string>
size_t bf_optimal_size(size_t v, size_t k) {
return static_cast<size_t>(std::ceil((v * k) / std::log(2.0)));
}
BloomFilter bf_init(size_t m, size_t k) {
BloomFilter bf;
bf.bits = std::vector<int>(m, 1);
bf.m = m;
bf.k = k;
return bf;
}
size_t bf_hash(const std::string& s, size_t i, size_t m) {
std::string salted = s + std::to_string(i);
unsigned char digest[SHA256_DIGEST_LENGTH];
SHA256(reinterpret_cast<const unsigned char*>(salted.data()), salted.size(), digest);
size_t result = 0;
for (int j = 0; j < 8; ++j)
result = (result << 8) | digest[j];
return result % m;
}
void bf_add(BloomFilter& bf, const std::string& s) {
for (size_t i = 0; i < bf.k; i++) {
size_t index = bf_hash(s, i, bf.m);
bf.bits[index] = 0;
}
}
bool bf_check(const BloomFilter& bf, const std::string& s) {
for (size_t i = 0; i < bf.k; i++) {
size_t index = bf_hash(s, i, bf.m);
if (bf.bits[index] != 0)
return false;
}
return true;
}
// j-th bit of SHA-256(s) — used as φ(s) in PSI
int phi_bit(const std::string& s, size_t j) {
unsigned char digest[SHA256_DIGEST_LENGTH];
SHA256(reinterpret_cast<const unsigned char*>(s.data()), s.size(), digest);
return (digest[j / 8] >> (7 - (j % 8))) & 1;
}