-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathprng.cpp
More file actions
80 lines (67 loc) · 1.38 KB
/
Copy pathprng.cpp
File metadata and controls
80 lines (67 loc) · 1.38 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
78
79
80
//
// Java Does USB
// Copyright (c) 2022 Manuel Bleichenbacher
// Licensed under MIT License
// https://opensource.org/licenses/MIT
//
// Reference C++ code common for Linux / macOS / Windows
//
#include "prng.hpp"
prng::prng(uint32_t init) : state(init), nbytes(0), bits(0) {}
void prng::reset(uint32_t init)
{
state = init;
nbytes = 0;
bits = 0;
}
uint32_t prng::next()
{
uint32_t x = state;
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
state = x;
return x;
}
void prng::fill(uint8_t *buf, int len)
{
for (int i = 0; i < len; i++)
{
if (nbytes == 0)
{
bits = next();
nbytes = 4;
}
buf[i] = bits;
bits >>= 8;
nbytes--;
}
}
void prng::fill(std::vector<uint8_t>& buf, int len)
{
if (len == -1 || len > buf.size())
len = static_cast<int>(buf.size());
fill(buf.data(), len);
}
int prng::verify(const uint8_t *buf, int len)
{
for (int i = 0; i < len; i++)
{
if (nbytes == 0)
{
bits = next();
nbytes = 4;
}
if (buf[i] != (uint8_t)bits)
return i;
bits >>= 8;
nbytes--;
}
return -1;
}
int prng::verify(const std::vector<uint8_t> &buf, int len)
{
if (len == -1 || len > buf.size())
len = static_cast<int>(buf.size());
return verify(buf.data(), len);
}