2 * Copyright 2021 The OpenSSL Project Authors. All Rights Reserved.
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
10 #include <openssl/evp.h>
11 #include <openssl/rand.h>
12 #include <openssl/bio.h>
13 #include <openssl/core_names.h>
14 #include "crypto/rand.h"
17 static int test_rand(void)
19 EVP_RAND_CTX
*privctx
;
20 OSSL_PARAM params
[2], *p
= params
;
21 unsigned char entropy1
[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 };
22 unsigned char entropy2
[] = { 0xff, 0xfe, 0xfd };
23 unsigned char outbuf
[3];
25 *p
++ = OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_ENTROPY
,
26 entropy1
, sizeof(entropy1
));
27 *p
= OSSL_PARAM_construct_end();
29 if (!TEST_ptr(privctx
= RAND_get0_private(NULL
))
30 || !TEST_true(EVP_RAND_CTX_set_params(privctx
, params
))
31 || !TEST_int_gt(RAND_priv_bytes(outbuf
, sizeof(outbuf
)), 0)
32 || !TEST_mem_eq(outbuf
, sizeof(outbuf
), entropy1
, sizeof(outbuf
))
33 || !TEST_int_le(RAND_priv_bytes(outbuf
, sizeof(outbuf
) + 1), 0)
34 || !TEST_int_gt(RAND_priv_bytes(outbuf
, sizeof(outbuf
)), 0)
35 || !TEST_mem_eq(outbuf
, sizeof(outbuf
),
36 entropy1
+ sizeof(outbuf
), sizeof(outbuf
)))
39 *params
= OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_ENTROPY
,
40 entropy2
, sizeof(entropy2
));
41 if (!TEST_true(EVP_RAND_CTX_set_params(privctx
, params
))
42 || !TEST_int_gt(RAND_priv_bytes(outbuf
, sizeof(outbuf
)), 0)
43 || !TEST_mem_eq(outbuf
, sizeof(outbuf
), entropy2
, sizeof(outbuf
)))
48 static int test_rand_uniform(void)
54 if (!test_get_libctx(&ctx
, NULL
, NULL
, NULL
, NULL
))
57 for (i
= 1; i
< 100; i
+= 13) {
58 x
= ossl_rand_uniform_uint32(ctx
, i
, &err
);
59 if (!TEST_int_eq(err
, 0)
60 || !TEST_uint_ge(x
, 0)
61 || !TEST_uint_lt(x
, i
))
64 for (i
= 1; i
< 100; i
+= 17)
65 for (j
= i
+ 1; j
< 150; j
+= 11) {
66 x
= ossl_rand_range_uint32(ctx
, i
, j
, &err
);
67 if (!TEST_int_eq(err
, 0)
68 || !TEST_uint_ge(x
, i
)
69 || !TEST_uint_lt(x
, j
))
75 OSSL_LIB_CTX_free(ctx
);
81 if (!TEST_true(RAND_set_DRBG_type(NULL
, "TEST-RAND", NULL
, NULL
, NULL
)))
84 ADD_TEST(test_rand_uniform
);