-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathblackrock.c
More file actions
77 lines (66 loc) · 1.98 KB
/
blackrock.c
File metadata and controls
77 lines (66 loc) · 1.98 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include "blackrock.h"
/*
* BlackRock2 Feistel cipher — bijective shuffle over [0, range).
* Based on masscan / VulnScanner implementation.
*
* We use a 64-bit Feistel network with variable half-widths
* derived from range, so the permutation stays within [0, range).
*/
/* round function — SipHash-inspired mix */
static uint64_t brock_round(uint64_t x, uint64_t key, int bits) {
x ^= key;
x ^= x >> 17;
x ^= x >> 31;
x ^= x >> 37;
x *= 0xbf58476d1ce4e5b9ULL;
x ^= x >> 27;
x *= 0x94d049bb133111ebULL;
x ^= x >> 31;
x &= (1ULL << bits) - 1;
return x;
}
void blackrock_init(blackrock_t *b, uint64_t range,
uint64_t seed, int rounds) {
b->range = range;
b->seed = seed;
b->rounds = rounds;
}
/*
* Cycle-walk Feistel: split index into two halves (a, b),
* apply rounds, reassemble. Reject if result >= range and
* iterate (statistically < 2 extra rounds on average).
*/
uint64_t blackrock_shuffle(blackrock_t *b, uint64_t index) {
if (b->range == 0) return 0;
if (b->range == 1) return 0;
/* find bit-width for each half */
uint64_t n = b->range;
int bits = 0;
while ((1ULL << bits) < n) bits++;
int half = bits / 2;
int half2 = bits - half;
uint64_t mask_lo = (1ULL << half) - 1;
uint64_t mask_hi = (1ULL << half2) - 1;
uint64_t val = index;
uint64_t a, c;
do {
a = val & mask_lo;
c = (val >> half) & mask_hi;
for (int r = 0; r < b->rounds; r++) {
uint64_t key = b->seed ^ (uint64_t)r * 0x9e3779b97f4a7c15ULL;
if (r & 1) {
uint64_t tmp = c ^ brock_round(a, key, half2);
tmp &= mask_hi;
c = a;
a = tmp;
} else {
uint64_t tmp = a ^ brock_round(c, key, half);
tmp &= mask_lo;
a = c;
c = tmp;
}
}
val = (c << half) | a;
} while (val >= n);
return val;
}