• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_ENTROPY) && defined(HITLS_CRYPTO_ENTROPY_SYS)
18 
19 #include <stdint.h>
20 #include <time.h>
21 #include "securec.h"
22 #include "bsl_err_internal.h"
23 #include "crypt_errno.h"
24 #include "es_noise_source.h"
25 
26 #define TIME_STAMP_ENTROPY_RCT_CUT_OFF 5
27 #define TIME_STAMP_ENTROPY_APT_WINDOW_SIZE 512
28 #define TIME_STAMP_ENTROPY_APT_CUT_OFF 39
29 
CRPT_Gettick(void)30 static uint64_t CRPT_Gettick(void)
31 {
32     uint64_t tick = 0;
33     struct timespec time;
34     if (clock_gettime(CLOCK_MONOTONIC, &time) == 0) {
35         tick = ((uint64_t)time.tv_sec & 0xFFFFFFFF) * 1000000000UL;
36         tick = tick + (uint64_t)time.tv_nsec;
37     }
38     return tick;
39 }
40 
ES_TimeStampRead(void * ctx,uint32_t timeout,uint8_t * buf,uint32_t bufLen)41 static int32_t ES_TimeStampRead(void *ctx, uint32_t timeout, uint8_t *buf, uint32_t bufLen)
42 {
43     if (buf == NULL || bufLen == 0) {
44         return -1;
45     }
46     (void)ctx;
47     (void)timeout;
48     for (uint32_t i = 0; i < bufLen; i++) {
49         buf[i] = CRPT_Gettick() & 0xFF;
50     }
51 
52     return CRYPT_SUCCESS;
53 }
54 
ES_TimeStampGetCtx(void)55 ES_NoiseSource *ES_TimeStampGetCtx(void)
56 {
57     ES_NoiseSource *ctx = BSL_SAL_Malloc(sizeof(ES_NoiseSource));
58     if (ctx == NULL) {
59         BSL_ERR_PUSH_ERROR(BSL_LIST_MALLOC_FAIL);
60         return NULL;
61     }
62     (void)memset_s(ctx, sizeof(ES_NoiseSource), 0, sizeof(ES_NoiseSource));
63     uint32_t len = strlen("timestamp");
64     ctx->name = BSL_SAL_Malloc(len + 1);
65     if (ctx->name == NULL) {
66         BSL_SAL_Free(ctx);
67         BSL_ERR_PUSH_ERROR(BSL_LIST_MALLOC_FAIL);
68         return NULL;
69     }
70     (void)strncpy_s(ctx->name, len + 1, "timestamp", len);
71 
72     ctx->para = NULL;
73     ctx->init = NULL;
74     ctx->read = ES_TimeStampRead;
75     ctx->deinit = NULL;
76     ctx->minEntropy = 5; // one byte bring 5 bits entropy
77     ctx->state.rctCutoff = TIME_STAMP_ENTROPY_RCT_CUT_OFF;
78     ctx->state.aptCutOff = TIME_STAMP_ENTROPY_APT_CUT_OFF;
79     ctx->state.aptWindowSize = TIME_STAMP_ENTROPY_APT_WINDOW_SIZE;
80     return ctx;
81 }
82 #endif