random.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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. #include "../testutil.h"
  10. /*
  11. * This is an implementation of the algorithm used by the GNU C library's
  12. * random(3) pseudorandom number generator as described:
  13. * https://www.mscs.dal.ca/~selinger/random/
  14. */
  15. static uint32_t test_random_state[31];
  16. uint32_t test_random(void) {
  17. static unsigned int pos = 3;
  18. if (pos == 31)
  19. pos = 0;
  20. test_random_state[pos] += test_random_state[(pos + 28) % 31];
  21. return test_random_state[pos++] / 2;
  22. }
  23. void test_random_seed(uint32_t sd) {
  24. int i;
  25. int32_t s;
  26. const unsigned int mod = (1u << 31) - 1;
  27. test_random_state[0] = sd;
  28. for (i = 1; i < 31; i++) {
  29. s = (int32_t)test_random_state[i - 1];
  30. test_random_state[i] = (uint32_t)((16807 * (int64_t)s) % mod);
  31. }
  32. for (i = 34; i < 344; i++)
  33. test_random();
  34. }