2
0

rand_test.c 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * Copyright 2021 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 <openssl/evp.h>
  10. #include <openssl/rand.h>
  11. #include <openssl/bio.h>
  12. #include <openssl/core_names.h>
  13. #include "crypto/rand.h"
  14. #include "testutil.h"
  15. static int test_rand(void)
  16. {
  17. EVP_RAND_CTX *privctx;
  18. OSSL_PARAM params[2], *p = params;
  19. unsigned char entropy1[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 };
  20. unsigned char entropy2[] = { 0xff, 0xfe, 0xfd };
  21. unsigned char outbuf[3];
  22. *p++ = OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_ENTROPY,
  23. entropy1, sizeof(entropy1));
  24. *p = OSSL_PARAM_construct_end();
  25. if (!TEST_ptr(privctx = RAND_get0_private(NULL))
  26. || !TEST_true(EVP_RAND_CTX_set_params(privctx, params))
  27. || !TEST_int_gt(RAND_priv_bytes(outbuf, sizeof(outbuf)), 0)
  28. || !TEST_mem_eq(outbuf, sizeof(outbuf), entropy1, sizeof(outbuf))
  29. || !TEST_int_le(RAND_priv_bytes(outbuf, sizeof(outbuf) + 1), 0)
  30. || !TEST_int_gt(RAND_priv_bytes(outbuf, sizeof(outbuf)), 0)
  31. || !TEST_mem_eq(outbuf, sizeof(outbuf),
  32. entropy1 + sizeof(outbuf), sizeof(outbuf)))
  33. return 0;
  34. *params = OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_ENTROPY,
  35. entropy2, sizeof(entropy2));
  36. if (!TEST_true(EVP_RAND_CTX_set_params(privctx, params))
  37. || !TEST_int_gt(RAND_priv_bytes(outbuf, sizeof(outbuf)), 0)
  38. || !TEST_mem_eq(outbuf, sizeof(outbuf), entropy2, sizeof(outbuf)))
  39. return 0;
  40. return 1;
  41. }
  42. static int test_rand_uniform(void)
  43. {
  44. uint32_t x, i, j;
  45. int err = 0, res = 0;
  46. OSSL_LIB_CTX *ctx;
  47. if (!test_get_libctx(&ctx, NULL, NULL, NULL, NULL))
  48. goto err;
  49. for (i = 1; i < 100; i += 13) {
  50. x = ossl_rand_uniform_uint32(ctx, i, &err);
  51. if (!TEST_int_eq(err, 0)
  52. || !TEST_uint_ge(x, 0)
  53. || !TEST_uint_lt(x, i))
  54. return 0;
  55. }
  56. for (i = 1; i < 100; i += 17)
  57. for (j = i + 1; j < 150; j += 11) {
  58. x = ossl_rand_range_uint32(ctx, i, j, &err);
  59. if (!TEST_int_eq(err, 0)
  60. || !TEST_uint_ge(x, i)
  61. || !TEST_uint_lt(x, j))
  62. return 0;
  63. }
  64. res = 1;
  65. err:
  66. OSSL_LIB_CTX_free(ctx);
  67. return res;
  68. }
  69. int setup_tests(void)
  70. {
  71. if (!TEST_true(RAND_set_DRBG_type(NULL, "TEST-RAND", NULL, NULL, NULL)))
  72. return 0;
  73. ADD_TEST(test_rand);
  74. ADD_TEST(test_rand_uniform);
  75. return 1;
  76. }