-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrand.c
84 lines (73 loc) · 1.68 KB
/
rand.c
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
81
82
83
84
#define _GNU_SOURCE
#include <stdint.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include "includes.h"
#include "rand.h"
static uint32_t x, y, z, w;
void rand_init(void)
{
x = time(NULL);
y = getpid() ^ getppid();
z = clock();
w = z ^ y;
}
uint32_t rand_next(void) //period 2^96-1
{
uint32_t t = x;
t ^= t << 11;
t ^= t >> 8;
x = y; y = z; z = w;
w ^= w >> 19;
w ^= t;
return w;
}
void rand_str(char *str, int len) // Generate random buffer (not alphanumeric!) of length len
{
while (len > 0)
{
if (len >= 4)
{
*((uint32_t *)str) = rand_next();
str += sizeof (uint32_t);
len -= sizeof (uint32_t);
}
else if (len >= 2)
{
*((uint16_t *)str) = rand_next() & 0xFFFF;
str += sizeof (uint16_t);
len -= sizeof (uint16_t);
}
else
{
*str++ = rand_next() & 0xFF;
len--;
}
}
}
void rand_alphastr(uint8_t *str, int len) // Random alphanumeric string, more expensive than rand_str
{
const char alphaset[] = "abcdefghijklmnopqrstuvw012345678";
while (len > 0)
{
if (len >= sizeof (uint32_t))
{
int i;
uint32_t entropy = rand_next();
for (i = 0; i < sizeof (uint32_t); i++)
{
uint8_t tmp = entropy & 0xff;
entropy = entropy >> 8;
tmp = tmp >> 3;
*str++ = alphaset[tmp];
}
len -= sizeof (uint32_t);
}
else
{
*str++ = rand_next() % (sizeof (alphaset));
len--;
}
}
}