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