entropy_hardware_alt.c 源码
2026/7/20大约 2 分钟附录源码附录MBED TLS熵源安全
entropy_hardware_alt.c — MBED TLS 硬件熵源适配
路径: components/security/mbedtls/port/src/entropy_hardware_alt.c
功能: 实现 MBED TLS 的硬件熵源(Entropy Source)接口,为 TLS 随机数生成器提供熵种子。通过系统 tick 值播种伪随机数生成器,确保每次 TLS 握手使用不同的随机数。
引用章节: 7.3.1 MBED TLS 加密组件
完整源码
/**
***********************************************************************************************************************
* Copyright (c) 2020, China Mobile Communications Group Co.,Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* @file entropy_hardware_alt.c
*
* @brief os related entropy generator
*
* @revision
* Date Author Notes
* 2020-11-25 OneOS Team First Version
***********************************************************************************************************************
*/
#if !defined(MBEDTLS_CONFIG_FILE)
#include "mbedtls/config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <os_clock.h>
#if defined(MBEDTLS_ENTROPY_HARDWARE_ALT)
static int os_generate_random_array(unsigned char *out_buf, size_t len)
{
int i, j;
int rand_data;
srand((unsigned int)os_tick_get_value());
for (i = 0; i < ((len + 3) & ~3) / 4; i++)
{
rand_data = rand();
for (j = 0; j < 4; j++)
{
if ((i * 4 + j) < len)
{
out_buf[i * 4 + j] = (unsigned char)(rand_data >> (j * 8));
}
else
{
break;
}
}
}
return 0;
}
int mbedtls_hardware_poll( void *data, unsigned char *output, size_t len, size_t *olen )
{
os_generate_random_array(output, len);
*olen = len;
return 0;
}
#endif关键说明
| 模块 | 说明 |
|---|---|
| 熵源播种 | srand((unsigned int)os_tick_get_value()) 使用系统启动后的 tick 值作为种子,确保每次启动熵值不同 |
| 随机数生成 | 使用标准 C 库 rand() 生成伪随机数,每次调用产生 4 字节(int 大小) |
| 字节填充 | 将 32 位随机数按字节拆分(rand_data >> (j * 8)),填充到输出缓冲区 |
| 对齐处理 | ((len + 3) & ~3) / 4 将长度向上对齐到 4 字节边界,确保生成足够的随机数据 |
| mbedtls_hardware_poll | 由 MBED TLS 的 CTR_DRBG 在需要熵时调用,*olen = len 表示成功生成全部请求的随机字节 |
| 适配宏 | 通过 MBEDTLS_ENTROPY_HARDWARE_ALT 启用,替代 MBED TLS 默认的熵源模块 |