1 /*
2 * This file is part of the openHiTLS project.
3 *
4 * openHiTLS is licensed under the Mulan PSL v2.
5 * You can use this software according to the terms and conditions of the Mulan PSL v2.
6 * You may obtain a copy of Mulan PSL v2 at:
7 *
8 * http://license.coscl.org.cn/MulanPSL2
9 *
10 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
11 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
12 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
13 * See the Mulan PSL v2 for more details.
14 */
15
16 #include "hitls_build.h"
17 #if defined(HITLS_CRYPTO_DRBG) || defined(HITLS_CRYPTO_CURVE25519) || \
18 defined(HITLS_CRYPTO_RSA) || defined(HITLS_CRYPTO_BN_RAND)
19
20 #include <stdlib.h>
21 #include "crypt_errno.h"
22 #include "bsl_err_internal.h"
23 #include "crypt_util_rand.h"
24
25 static CRYPT_EAL_RandFunc g_randFunc = NULL;
26 static CRYPT_EAL_RandFuncEx g_randFuncEx = NULL;
27
CRYPT_RandRegist(CRYPT_EAL_RandFunc func)28 void CRYPT_RandRegist(CRYPT_EAL_RandFunc func)
29 {
30 g_randFunc = func;
31 }
32
CRYPT_Rand(uint8_t * rand,uint32_t randLen)33 int32_t CRYPT_Rand(uint8_t *rand, uint32_t randLen)
34 {
35 if (g_randFunc == NULL) {
36 BSL_ERR_PUSH_ERROR(CRYPT_NO_REGIST_RAND);
37 return CRYPT_NO_REGIST_RAND;
38 }
39 int32_t ret = g_randFunc(rand, randLen);
40 if (ret != CRYPT_SUCCESS) {
41 BSL_ERR_PUSH_ERROR(ret);
42 }
43 return ret;
44 }
45
CRYPT_RandRegistEx(CRYPT_EAL_RandFuncEx func)46 void CRYPT_RandRegistEx(CRYPT_EAL_RandFuncEx func)
47 {
48 g_randFuncEx = func;
49 }
50
CRYPT_RandEx(void * libCtx,uint8_t * rand,uint32_t randLen)51 int32_t CRYPT_RandEx(void *libCtx, uint8_t *rand, uint32_t randLen)
52 {
53 #if defined(HITLS_CRYPTO_PROVIDER)
54 int32_t ret = 0;
55 if (g_randFuncEx != NULL) {
56 ret = g_randFuncEx(libCtx, rand, randLen);
57 } else if (g_randFunc != NULL) {
58 ret = g_randFunc(rand, randLen);
59 } else {
60 ret = CRYPT_NO_REGIST_RAND;
61 }
62 if (ret != CRYPT_SUCCESS) {
63 BSL_ERR_PUSH_ERROR(ret);
64 }
65 return ret;
66 #else
67 (void) libCtx;
68 return CRYPT_Rand(rand, randLen);
69 #endif
70 }
71
72 #endif
73