xref: /openssl/test/testutil/random.c (revision e9a5932d)
1 /*
2  * Copyright 2019 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9 
10 #include "../testutil.h"
11 
12 /*
13  * This is an implementation of the algorithm used by the GNU C library's
14  * random(3) pseudorandom number generator as described:
15  *      https://www.mscs.dal.ca/~selinger/random/
16  */
17 static uint32_t test_random_state[31];
18 
test_random(void)19 uint32_t test_random(void) {
20     static unsigned int pos = 3;
21 
22     if (pos == 31)
23         pos = 0;
24     test_random_state[pos] += test_random_state[(pos + 28) % 31];
25     return test_random_state[pos++] / 2;
26 }
27 
test_random_seed(uint32_t sd)28 void test_random_seed(uint32_t sd) {
29     int i;
30     int32_t s;
31     const unsigned int mod = (1u << 31) - 1;
32 
33     test_random_state[0] = sd;
34     for (i = 1; i < 31; i++) {
35         s = (int32_t)test_random_state[i - 1];
36         test_random_state[i] = (uint32_t)((16807 * (int64_t)s) % mod);
37     }
38     for (i = 34; i < 344; i++)
39         test_random();
40 }
41