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 #ifdef HITLS_CRYPTO_ENTROPY
18
19 #include <stdint.h>
20 #include <unistd.h>
21 #ifdef HITLS_CRYPTO_ENTROPY_GETENTROPY
22 #include <sys/random.h>
23 #endif
24 #ifdef HITLS_CRYPTO_ENTROPY_DEVRANDOM
25 #include <fcntl.h>
26 #include <errno.h>
27 #endif
28 #include "securec.h"
29 #include "bsl_err_internal.h"
30 #include "crypt_errno.h"
31 #include "entropy_seed_pool.h"
32
33
ENTROPY_SysEntropyGet(void * ctx,uint8_t * buf,uint32_t bufLen)34 uint32_t ENTROPY_SysEntropyGet(void *ctx, uint8_t *buf, uint32_t bufLen)
35 {
36 (void)ctx;
37
38 #if defined(HITLS_CRYPTO_ENTROPY_GETENTROPY) || defined(HITLS_CRYPTO_ENTROPY_DEVRANDOM)
39 uint32_t res = 0;
40 #if defined(HITLS_CRYPTO_ENTROPY_GETENTROPY)
41 if (getentropy(buf, bufLen) == 0) {
42 return bufLen;
43 }
44 #endif
45
46 #if defined(HITLS_CRYPTO_ENTROPY_DEVRANDOM)
47 int32_t fd = open("/dev/random", O_RDONLY);
48 if (fd == -1) {
49 BSL_ERR_PUSH_ERROR(CRYPT_DRBG_FAIL_GET_ENTROPY);
50 return 0;
51 }
52 uint32_t left = bufLen;
53 uint8_t *tmp = buf;
54 do {
55 int32_t count = (int32_t)read(fd, tmp, left);
56 if (count == -1 && errno == EINTR) {
57 continue;
58 } else if (count == -1) {
59 break;
60 }
61 left -= (uint32_t)count;
62 tmp += (uint32_t)count;
63 } while (left > 0);
64 close(fd);
65 if (left > 0) {
66 BSL_ERR_PUSH_ERROR(CRYPT_DRBG_FAIL_GET_ENTROPY);
67 }
68 res = bufLen - left;
69 #endif
70 return res;
71 #else
72 (void)buf;
73 (void)bufLen;
74 BSL_ERR_PUSH_ERROR(CRYPT_DRBG_FAIL_GET_ENTROPY);
75 return 0;
76 #endif
77 }
78
79 #endif
80