1 // SPDX-License-Identifier: BSD-2-Clause
2 /*
3  * Copyright (c) 2021 Huawei Technologies Co., Ltd
4  */
5 
6 #include <compiler.h>
7 #include <crypto/crypto.h>
8 #include <mbedtls/bignum.h>
9 #include <stddef.h>
10 #include <tee_api_defines.h>
11 #include <tee_api_types.h>
12 
13 #include "mbed_helpers.h"
14 
15 /* Generate random number 1 <= n < max */
mbed_gen_random_upto(mbedtls_mpi * n,mbedtls_mpi * max)16 TEE_Result mbed_gen_random_upto(mbedtls_mpi *n, mbedtls_mpi *max)
17 {
18 	size_t sz = mbedtls_mpi_size(max);
19 	bool found = false;
20 	int mres = 0;
21 
22 	do {
23 		mres = mbedtls_mpi_fill_random(n, sz, mbd_rand, NULL);
24 		if (mres)
25 			return TEE_ERROR_BAD_STATE;
26 		if (mbedtls_mpi_bitlen(n) != 0 &&
27 		    mbedtls_mpi_cmp_mpi(n, max) == -1)
28 			found = true;
29 	} while (!found);
30 
31 	return TEE_SUCCESS;
32 }
33 
34