implement basic pseudo random number generator
Stefan Schuermans

Stefan Schuermans commited on 2012-04-04 22:27:02
Showing 2 changed files, with 74 additions and 0 deletions.

... ...
@@ -0,0 +1,55 @@
1
+#include "random.h"
2
+
3
+// FIXME: this random number generator is most likely not very good
4
+
5
+/// state of the linear feedback shift register (LFSR)
6
+static unsigned long random_lfsr = 1;
7
+
8
+/// step LFSR
9
+static void random_step(void)
10
+{
11
+  random_lfsr = (random_lfsr >> 1) ^ (-(random_lfsr & 1U) & 0xD0000001U);
12
+}
13
+
14
+/**
15
+ * @brief provide entropy
16
+ * @param[in] ptr pointer to buffer containing entropy
17
+ * @param[in] sz size of buffer
18
+ */
19
+void random_provide_entropy(const void *ptr, unsigned int sz)
20
+{
21
+  const unsigned char *src = ptr;
22
+  unsigned char val;
23
+  unsigned int bit;
24
+
25
+  for ( ; sz > 0; --sz) {
26
+    val = *src++;
27
+    for (bit = 0; bit < 8; ++bit) {
28
+      if (val & 1)
29
+        random_step();
30
+      val >>= 1;
31
+    }
32
+  }
33
+}
34
+
35
+/**
36
+ * @brief get random data
37
+ * @param[in] ptr pointer to buffer to fill with random data
38
+ * @param[in] sz size of buffer to fill
39
+ */
40
+void random_get_data(void *ptr, unsigned int sz)
41
+{
42
+  unsigned char *dest = ptr;
43
+  unsigned char val;
44
+  unsigned int bit;
45
+
46
+  for ( ; sz > 0; --sz) {
47
+    val = 0;
48
+    for (bit = 0; bit < 8; ++bit) {
49
+      random_step();
50
+      val = val << 1 | (random_lfsr & 1);
51
+    }
52
+    *dest++ = val;
53
+  }
54
+}
55
+
... ...
@@ -0,0 +1,19 @@
1
+#ifndef RANDOM_H
2
+#define RANDOM_H
3
+
4
+/**
5
+ * @brief provide entropy
6
+ * @param[in] ptr pointer to buffer containing entropy
7
+ * @param[in] sz size of buffer
8
+ */
9
+void random_provide_entropy(const void *ptr, unsigned int sz);
10
+
11
+/**
12
+ * @brief get random data
13
+ * @param[in] ptr pointer to buffer to fill with random data
14
+ * @param[in] sz size of buffer to fill
15
+ */
16
+void random_get_data(void *ptr, unsigned int sz);
17
+
18
+#endif // #ifdef RANDOM_H
19
+
0 20