Lightweight TLS protocol stack and Internet of Things device

By designing a lightweight TLS protocol stack and utilizing the internal resources of the device chip to construct a hardware entropy source and a unified network interface, the hardware binding and resource consumption problems of TLS encryption in IoT devices are solved, achieving low-cost and high-efficiency secure communication.

CN121887475APending Publication Date: 2026-04-17JIANGYIN ACREL ELECTRICAL APPLIANCE MFGCO +2
View PDF 0 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-12-30
Publication Date
2026-04-17

AI Technical Summary

Technical Problem

Existing IoT devices suffer from problems such as strong hardware binding, high resource consumption, inability to be ported across platforms, and unstable entropy sources when implementing TLS encryption, resulting in high hardware costs, complex development, and low efficiency.

Method used

A lightweight TLS protocol stack was designed, including a TLS encryption module, a network interface standardization module, and a random number entropy source logic component. The hardware entropy source array is constructed using the internal logic gates and I/O pins of the device chip, providing a unified network adapter interface, supporting multiple communication modules, and optimizing certificate verification and data processing.

Benefits of technology

It reduces hardware costs, decreases resource consumption, improves cross-platform portability and code reuse, enhances development efficiency and security, and is adaptable to a variety of low-cost microcontroller devices.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121887475A_ABST
    Figure CN121887475A_ABST
Patent Text Reader

Abstract

The invention discloses a lightweight TLS protocol stack and Internet of Things equipment. The lightweight TLS protocol stack comprises a TLS encryption module used for carrying out handshake negotiation with an opposite terminal and carrying out encryption, decryption and transmission management on data; the network interface standardization module is used for providing network adapters of different types of communication modules and managing the communication modules through a unified interface specification; wherein the TLS encryption module comprises a random number entropy source logic component which is used for selectively configuring a plurality of delay lines with length and path differences to form a hardware entropy source array, sampling random jitter generated by pulse signals input into the delay lines by using the hardware entropy source array to obtain physical random bits, and transmitting the physical random bits to the random number entropy source logic component; the physical random bits are used for generating random numbers required by handshake negotiation; the delay line is composed of a logic gate and a configurable IO pin in an equipment chip. According to the invention, the hardware dependence can be reduced, and various low-cost chips can be flexibly adapted.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of Internet of Things (IoT) communication technology, specifically to a lightweight TLS protocol stack and IoT device. Background Technology

[0002] With the rapid development of IoT technology, a massive number of devices are connecting to the network and communicating data, making communication security an increasingly critical concern. Transport Layer Security (TLS) protocol, as the cornerstone for ensuring data confidentiality, integrity, and authentication, continues to see growing demand in the IoT field.

[0003] Current technical solutions for implementing TLS encryption in embedded gateways all have their limitations. First, they rely on the built-in SSL / TLS hardware encryption functions of communication modules (such as specific 4G or Wi-Fi modules). These functions are invoked via module AT commands, requiring specific hardware and preventing cross-module reuse. This results in high hardware costs, limited functionality, high code-hardware coupling, and poor standardization. Second, using general-purpose libraries like OpenSSL often results in memory consumption exceeding 100KB, making it unsuitable for low-cost microcontrollers with less than 64KB of RAM. This forces the use of expensive, high-performance processors, significantly increasing costs. Third, while smaller TLS protocol libraries (such as mbedtls and WolfSSL) can be customized for microcontroller applications, their default configurations still consume significant resources, and their overall architecture remains tightly coupled with the hardware. Developers must repeatedly write drivers for different network interfaces, leading to low code reusability and high porting costs. Furthermore, existing random number generation solutions either rely on software pseudo-random number algorithms, which have security vulnerabilities on simple hardware platforms lacking stable entropy sources, or they rely on dedicated hardware random number generators (HRNGs), which cannot be ported across platforms.

[0004] In summary, existing technologies in IoT scenarios suffer from strong hardware constraints and high resource consumption, lacking a lightweight solution that can both guarantee a high-quality entropy source and flexibly adapt to various low-cost chips. Summary of the Invention

[0005] The purpose of this invention is to overcome the shortcomings of the existing technology and provide a lightweight TLS protocol stack and Internet of Things device.

[0006] To achieve the above objectives, the first aspect of this invention designs a lightweight TLS protocol stack, comprising: The TLS encryption module is used for handshake negotiation with the peer, as well as for data encryption, decryption, and transmission management. A network interface standardization module is used to provide network adapters for different types of communication modules and to manage the communication modules through a unified interface specification. The TLS encryption module includes a random number entropy source logic component, which is used to selectively configure multiple delay lines with different lengths and paths to form a hardware entropy source array. The hardware entropy source array samples the random jitter generated by the pulse signal input to the delay line to obtain physical random bits. The physical random bits are used to generate random numbers required for handshake negotiation. The delay line is composed of logic gates and configurable I / O pins inside the device chip.

[0007] Furthermore, the TLS encryption module also includes a timestamp verification component, used to estimate a dynamic confidence window of the current time based on the relative time drift rate between the pre-acquired anchor time and the internal clock when verifying the validity of the peer certificate in the absence of an external time source, and to perform certificate validity verification based on the dynamic confidence window; wherein, the size of the dynamic confidence window is proportional to the duration elapsed since the anchor time, and the relative time drift rate is calibrated through security heartbeat messages exchanged between devices.

[0008] Furthermore, the TLS encryption module also includes a cipher suite management component, used to adjust the priority order of cipher suites to be negotiated during handshake negotiation with the peer according to the current operating status of the device. The operating status includes at least one of battery level, CPU load, or network threat level. When the battery level is lower than a preset threshold, the priority of cipher suites supported by the hardware accelerator is increased. The negotiated cipher suites are used to generate the session master key.

[0009] Furthermore, the TLS encryption module also includes a handshake management component, used to generate a preliminary master key during handshake negotiation, store the preliminary master key in a pre-allocated static memory pool; perform a hash operation on the data in the static memory area where the preliminary master key is stored in the static memory pool to obtain the corresponding hash value; compare the hash value with the expected value derived from the preliminary master key, and terminate the handshake connection if the comparison result does not match; wherein, the preliminary master key and the random number are used as input data when generating the session master key from the negotiated cipher suite.

[0010] Furthermore, the handshake management component is also used to verify, upon receiving a session recovery request from the peer, whether the secondary credential carried in the session recovery request is derived from the master key of the previous session; if so, the session recovery request is approved.

[0011] Furthermore, the TLS encryption module also includes a data transmission and reception management component, which is used to set up multiple data priority queues for the pre-configured transmit ring buffer and receive ring buffer when encrypting, decrypting and managing the transmission of data. The priority of the multiple data priority queues is determined by weighting according to the predefined priority of the data type stored therein; and the data blocks in the multiple data priority queues are scheduled and processed by a weighted round-robin scheduler.

[0012] Furthermore, when the data transceiver management component performs encryption, decryption, and transmission management on the data, it is also used to identify the fixed header portion of the application layer protocol message with a known fixed format in the application layer data before the application layer data enters the transmission ring buffer, perform pre-encryption processing on the fixed header portion, and store the pre-encryption result; when sending the application layer protocol message, it encrypts the variable payload portion of the application layer protocol message, and concatenates the pre-encryption result with the encrypted variable payload portion before sending.

[0013] Furthermore, the TLS encryption module also includes a certificate verification component, which caches the hash values ​​of the peer certificate and the CA certificates in its verification path after successful verification of the peer certificate, in order to form a fingerprint chain.

[0014] Furthermore, the certificate verification component is also used to compare the CA certificate hash value embedded in the peer certificate with the locally cached fingerprint chain when verifying the peer certificate if the peer's CA certificate cannot be downloaded; if a fingerprint chain that can be traced back to a locally preset trusted root certificate is found, a communication connection is established with the peer; the communication connection is marked as a cache-verified connection, and the peer's access permissions are restricted to allow only data reporting.

[0015] A second aspect of the present invention provides an Internet of Things (IoT) device configured with the lightweight TLS protocol stack described in the first aspect.

[0016] The advantages and beneficial effects of this invention are as follows: By directly utilizing the logic gates and configurable I / O pins inside the device's main control chip to construct a hardware entropy source array through the random number entropy source logic component, it replaces the traditional solution that relies on external dedicated security chips or the built-in encryption function of the communication module. This significantly reduces the system's dependence on specific hardware while ensuring high-quality random number generation. High-security communication effects can be achieved on low-cost microcontrollers such as low-cost IoT gateways, greatly reducing hardware costs. Simultaneously, the memory and storage space requirements of the protocol stack are reduced during runtime, decreasing resource consumption. The development cycle required for adding new network interfaces is shortened, and the amount of code modification required for cross-platform porting is significantly reduced, greatly improving development efficiency and code reusability, and shortening the product development and iteration cycle. Attached Figure Description

[0017] Figure 1 This is a schematic diagram of the lightweight TLS protocol stack of the present invention; Figure 2 This is a flowchart of the protocol stack usage method of the present invention; Figure 3 This is a schematic diagram of an application scenario of the present invention. Detailed Implementation

[0018] The specific embodiments of the present invention will be further described below with reference to the accompanying drawings and examples. The following examples are only used to more clearly illustrate the technical solutions of the present invention and should not be construed as limiting the scope of protection of the present invention.

[0019] according to Figure 1 As shown, the present invention is a lightweight TLS protocol stack that can be configured in IoT devices, such as IoT gateways. The lightweight TLS protocol stack 100 includes: The TLS encryption module 110 is used to conduct handshake negotiation with the peer, and to encrypt, decrypt and manage the transmission of data; The network interface standardization module 120 is used to provide network adapters for different types of communication modules and to manage the communication modules through a unified interface specification. The TLS encryption module includes a random number entropy source logic component 111, which is used to selectively configure multiple delay lines with different lengths and paths to form a hardware entropy source array. The hardware entropy source array samples the random jitter generated by the pulse signal input to the delay line to obtain physical random bits. The physical random bits are used to generate random numbers required for handshake negotiation. The delay line is composed of logic gates and configurable I / O pins inside the device chip.

[0020] The TLS encryption module is responsible for executing the complete TLS secure communication process, including initiating and completing handshake negotiation with the peer (such as cloud server, data acquisition device), exchanging and verifying digital certificates, generating session keys, and based on these keys, encrypting, decrypting, and managing the orderly transmission of application layer data.

[0021] The role of the network interface standardization module is to abstract and unify the diverse underlying physical communication hardware. Through unified encapsulation and extension of the network interface, it handles data interaction with the TLS encryption module, providing a standardized interface for portability and reducing the coupling between driver code and the hardware platform. Specifically, the network interface standardization module provides network adapters for different types of communication modules (such as 4G modules based on AT commands, Wi-Fi modules based on SPI / UART, and Ethernet controllers based on MAC layer drivers), and abstracts all adapter operations (such as initialization, data sending (send), and data receiving (recv) into a unified interface specification (such as the `net_adapter_t` structure) for management. This completely decouples the upper-layer TLS encryption logic from the specific network hardware.

[0022] The interaction information (ClientHello message or ServerHello message) during the handshake negotiation process between the TLS encryption module and the peer contains random numbers (such as ClientHello.random or ServerHello.random). These random numbers are essential materials for generating session keys and building the foundation of secure communication. Generating high-quality random numbers requires a reliable high-quality entropy source, which is implemented by a random number entropy source logic component in this embodiment of the invention.

[0023] This random number entropy source logic component utilizes the abundant logic gates and configurable I / O pins within the microcontroller to construct multiple delay lines with slightly different lengths and paths. By simultaneously inputting a high-frequency clock pulse into these delay lines, due to subtle differences in semiconductor manufacturing processes and fluctuations in operating temperature and voltage, the propagation speed of the signal along each path will produce minute, unpredictable random differences, resulting in random phase jitter between the output signals of each path. Then, a high-speed timer samples combinations of these signals (such as XOR values) to obtain high-quality physical random bits. These physical random bits serve as high-quality raw entropy data, upon which high-quality random numbers can be generated, improving the security of handshake negotiation and communication encryption.

[0024] Specifically, the random number entropy source logic component abstracts a "delay line configuration layer" at the software level. Through register configuration, it dynamically "weaves" and "selects" available delay paths, enabling the algorithm to find a usable entropy source array on different microcontroller models. Because this hardware entropy source array does not rely on a single dedicated device, but rather transforms the inherent and diverse physical random phenomena within the device's main control chip into entropy sources through intelligent configuration, it achieves decoupling from the hardware and facilitates cross-platform portability.

[0025] In one possible implementation, the random number entropy source logic component can also employ a multi-source entropy mixing strategy. This is achieved by setting a unified interface that can connect not only to the aforementioned delay line hardware entropy source array but also to other available hardware entropy sources such as the chip's built-in true random number generator and ADC noise sampling. Then, an intelligent scheduling algorithm dynamically evaluates the output quality and health status of each entropy source in real time and adjusts its sampling weight accordingly, outputting the mixed entropy source data. Finally, a strong cryptographic hash function such as SHA-256 is used to hash and obfuscate the mixed entropy source data, eliminating correlations and generating higher-quality entropy source data.

[0026] This invention, through its random number entropy source logic component, directly utilizes the logic gates and configurable I / O pins within the device's main control chip to construct a hardware entropy source array. This replaces the traditional approach that relies on external dedicated security chips or the built-in encryption functions of communication modules. Thus, while ensuring high-quality random number generation, it significantly reduces the system's dependence on specific hardware. High-security communication can be achieved on low-cost microcontrollers such as low-cost IoT gateways, greatly reducing hardware costs. Simultaneously, the protocol stack's memory and storage space requirements are reduced during runtime, minimizing resource consumption. The development cycle for adding new network interfaces is shortened, and the amount of code modification required for cross-platform porting is significantly reduced, greatly improving development efficiency and code reusability, and shortening product development and iteration cycles.

[0027] To ensure certificate validity verification can be performed and improve the accuracy of certificate validity verification in environments lacking reliable time sources, such as offline or weak network conditions, a preferred embodiment of the present invention includes a timestamp verification component 112. This component is used to estimate a dynamic confidence window of the current time based on the relative time drift rate between a pre-acquired anchor time and an internal clock when verifying the validity of a peer certificate in the absence of an external time source, and to perform certificate validity verification based on the dynamic confidence window. The size of the dynamic confidence window is proportional to the elapsed time since the anchor time, and the relative time drift rate is calibrated using secure heartbeat messages exchanged between devices.

[0028] When a device can connect to a trusted time source (such as upon initial power-on or periodic synchronization), an authoritative anchor time is acquired, and the device's internal clock reading is recorded at that moment. A relative timeline is then maintained using the internal clock (even with drift). When verifying the validity of a peer certificate, absolutely accurate current time is not required. Instead, a dynamic confidence window (i.e., a floating time window) centered on the estimated current time is calculated based on the anchor time, the elapsed time since the anchor, and the estimated clock drift rate. The size of this window is proportional to the elapsed time since the anchor time; the longer the time, the greater the uncertainty regarding accumulated clock drift, and the larger the window becomes. The timestamp verification component performs verification by determining whether the certificate's validity period overlaps with this dynamic confidence window.

[0029] In addition, devices can calibrate clock drift rates by exchanging secure heartbeat messages, forming a local, dynamically adjusted "trusted time consensus network". This allows them to maintain high-precision time judgment even when they cannot connect to an external time server, greatly improving the resilience of timestamp verification in offline or weak network environments.

[0030] To ensure communication security while intelligently balancing the energy consumption and performance of IoT devices, extending device battery life, and optimizing resource utilization, a preferred embodiment of the present invention includes a cipher suite management component 113 in the TLS encryption module. This component adjusts the priority order of cipher suites to be negotiated during handshake negotiation with the peer based on the device's current operating status. The operating status includes at least one of battery level, CPU load, or network threat level. Specifically, when the battery level is below a preset threshold, the priority of cipher suites supported by the hardware accelerator is increased. The negotiated cipher suites are used to generate the session master key.

[0031] The cipher suite management component introduces context-aware capabilities, dynamically adjusting the priority of the cipher suite list provided during TLS handshake negotiation based on the device's current operating status (such as battery level, CPU load, and network threat awareness level). For example, when the device detects that the battery level is below a preset threshold (e.g., 20%), the component uses a built-in security-energy consumption decision model to prioritize cipher suites supported by hardware encryption engines (such as AES-NI or on-chip cryptographic algorithm accelerators) in the handshake request, while reducing the priority of cipher suites that rely entirely on software computation. This encourages the server to choose encryption algorithm combinations that meet security requirements while minimizing device power consumption during negotiation. The final negotiated cipher suite is used to generate the session master key, thus enabling proactive management of device energy efficiency at the protocol level.

[0032] To prevent key material leakage due to memory pollution or malicious tampering during TLS handshake negotiation, a preferred embodiment of the present invention further includes a handshake management component 114, used to generate a preliminary master key during handshake negotiation, store the preliminary master key in a pre-allocated static memory pool; perform a hash operation on the data in the static memory area storing the preliminary master key in the static memory pool to obtain the corresponding hash value; compare the hash value with the expected value derived from the preliminary master key, and terminate the handshake connection if the comparison result does not match; wherein, the preliminary master key and the random number are used as input data when generating the session master key from the negotiated cipher suite.

[0033] The handshake management component stores sensitive temporary data during the handshake process through a pre-allocated static memory pool. The memory address of the static memory pool is fixed and physically isolated from the business logic memory, avoiding fragmentation and unpredictability that may be caused by dynamic memory allocation.

[0034] In the crucial handshake step, after generating the pre-master secret, this key is stored in a fixed area of ​​a static memory pool. The component performs a fast hash operation (e.g., calculating a CRC32 value) on the data in this storage area to generate a memory fingerprint. This fingerprint is then compared to an expected value derived from the pre-master secret. If they do not match, it indicates that the data in memory may have been accidentally modified or subjected to a tampering attack after generation, and the component immediately terminates the handshake connection to prevent key leakage. Here, the pre-master secret, along with the random number (client-side random number) generated by the aforementioned random number entropy source logic component, serves as input. Combined with the peer's random number, and through a negotiated cryptographic suite (such as a standard pseudo-random function PRF), the final session master secret is derived for encrypting subsequent application data.

[0035] To enhance the security of TLS session recovery and prevent session credentials from being replayed or forged, a preferred embodiment of the present invention is that the handshake management component 114 is further configured to verify, upon receiving a session recovery request from the peer, whether the secondary credential carried in the session recovery request is derived from the master key of the previous session; if so, the session recovery request is approved.

[0036] TLS session recovery is achieved through a session state cache reuse mechanism. An algorithm manages the session cache, and a configuration option allows setting the maximum number of entries for session recovery. The validity of the handshake session is double-verified, simultaneously verifying time validity and using a counter to limit the number of reuses, reducing memory leaks and high resource consumption issues caused by repeated handshakes.

[0037] When the peer wishes to resume a previous TLS session, it sends a session resumption request to the local end. In addition to verifying the standard Session ID and session lifecycle, the handshake management component requires the client to include a secondary credential in this request. This secondary credential is a unique proof derived from the master key of the previous successful session using a specific algorithm. The process verifies whether this secondary credential can form a coherent chain of trust with the previously stored session information. Session resumption is only permitted if the credential is valid and matches, effectively preventing credential replay or forgery.

[0038] To optimize the processing efficiency of data transmission and reception, a preferred embodiment of the present invention is that the TLS encryption module further includes a data transmission and reception management component 115, which is used to set up multiple data priority queues for the pre-configured transmit ring buffer and receive ring buffer when encrypting, decrypting and managing the transmission of data. The priority of the multiple data priority queues is determined by weighting according to the predefined priority of the data type stored therein; and the data blocks in the multiple data priority queues are scheduled and processed by a weighted round-robin scheduler.

[0039] The data transceiver management component is pre-configured with a sending-end encryption ring buffer and a receiving-end decryption ring buffer. The data processing flow in the sending-end encryption buffer is as follows: plaintext is written at the application layer → TLS encryption → ciphertext is stored in the ring buffer → asynchronous transmission via the network interface; when the buffer is full, hardware flow control or application-end blocking is triggered. The data processing flow in the receiving-end decryption buffer is as follows: ciphertext is received at the network interface → stored in the ring buffer → TLS decryption → plaintext is read at the application layer; when the buffer is empty, a retransmission request is triggered.

[0040] In this embodiment of the invention, the two buffers of the data transceiver management component each define multiple data priority queues. The priority of these data priority queues is determined by a predefined weighted average of the priorities of the data types stored within them. For example, data can be divided into different priorities such as "control signaling," "real-time sensor data," and "batch firmware data" based on business importance. The encryption / decryption engine does not simply process data blocks in the buffers sequentially. Instead, it uses a weighted round-robin scheduler to prioritize and process data blocks in high-priority queues based on predefined priority weights, performing encryption (send) or decryption (receive) operations on them. This ensures that critical business data receives priority processing when resources are scarce, guaranteeing the real-time performance of the system.

[0041] To reduce the computational overhead of real-time encryption for repetitive data, a preferred embodiment of the present invention is that, when the data transceiver management component 115 performs encryption, decryption, and transmission management on the data, it further identifies the fixed header portion of the application layer protocol message with a known fixed format in the application layer data before the application layer data enters the transmission ring buffer, performs pre-encryption processing on the fixed header portion, and stores the pre-encryption result; when the application layer protocol message is transmitted, it encrypts the variable payload portion of the application layer protocol message, and concatenates the pre-encryption result with the encrypted variable payload portion before transmission.

[0042] In this embodiment of the invention, the data transmission and reception management component also has encrypted streaming preprocessing capabilities. For application layer protocol messages with known fixed formats that are frequently used by the device (such as MQTT Connect messages, CoAP headers, etc.), the component can perform pre-analysis before the application layer data is submitted for transmission. It identifies the fixed header portions in these messages and pre-encrypts these headers using the encryption key of the current session, caching the encryption results. When it is actually necessary to send this type of message, the component only needs to encrypt the variable payload portion (such as sensor values, command parameters) in the message in real time, and then quickly concatenate the cached pre-encrypted header with the encrypted payload to complete the encrypted transmission of the entire message. This avoids the large amount of computation required to repeatedly encrypt the same header portion for each transmission, significantly improving processing efficiency.

[0043] To address the issue of the inability to verify a complete certificate chain in offline or high-latency network environments and improve connection success rates under weak network conditions, a preferred embodiment of the present invention includes a certificate verification component 116 in which, after successfully verifying the peer certificate, the hash value of the peer certificate and the CA certificate in its verification path is cached to form a fingerprint chain.

[0044] The certificate verification component 116 is also used to, when verifying the peer's certificate, compare the CA certificate hash value embedded in the peer's certificate with the locally cached fingerprint chain if the peer's CA certificate cannot be downloaded; if a fingerprint chain that can be traced back to a locally preset trusted root certificate is found, then a communication connection is established with the peer; the communication connection is marked as a connection based on cache verification, and the peer's access permissions are restricted to only allowing data reporting.

[0045] CA certificates (Certificate Authority Certificates) play a central role as trust anchors and trust transmitters in digital certificate and public key infrastructure (PKI) systems. After successfully verifying a peer certificate online, the certificate verification component not only caches the certificate itself, but also extracts and caches the hash values ​​(i.e., fingerprints) of all CA certificates (including intermediate CAs and root CAs) along its entire verification path, forming a local fingerprint chain.

[0046] When a new certificate with the same root certificate but issued by a new intermediate CA is encountered in a weak network environment, even if the intermediate CA certificate that issued the new certificate cannot be downloaded immediately, certificate verification can be performed by reading the CA certificate fingerprint information embedded in the new certificate and comparing it with the locally cached fingerprint chain. If a complete fingerprint chain that can be matched and traced back to the device's pre-installed trusted root certificate can be found, the certificate verification component can complete the initial offline verification based on this dynamic trust chain, thereby allowing the connection to be established.

[0047] As a security boundary, connections established in this manner are marked as cache-based verification connections, and their access permissions are restricted (e.g., only data reporting is allowed, while high-risk operations such as configuration modifications are prohibited). Once the network recovers, the system can require a full online certificate verification for the connection to remove the restrictions. This achieves a good balance between security and connection availability under adverse network conditions.

[0048] In one implementation, the lightweight TLS protocol stack of the present invention also provides a unified API interface for the application layer, as shown in the following code: int tls_connect(const char *host, uint16_t port); int tls_send(const uint8_t *data, size_t len); int tls_recv(uint8_t *buf, size_t max_len); The application layer only needs to call these three API interfaces to communicate with the TLS server. The `int tls_connect(const char *host, uint16_t port)` function initiates a TLS secure connection with the specified host and port. This function encapsulates the complete TCP connection establishment and TLS handshake negotiation (including certificate verification, key exchange, and all other steps). The `int tls_send(const uint8_t *data, size_t len)` function sends data through the established TLS secure connection. Internally, the function automatically encrypts the plaintext data `data` before sending it over the underlying network. The `int tls_recv(uint8_t *buf, size_t max_len)` function receives data from the TLS secure connection. Internally, the function automatically handles the reception and decryption of data packets and stores the decrypted plaintext in the buffer `buf`.

[0049] This set of APIs completely decouples application-layer business logic from complex secure communication protocols, significantly reducing development barriers and maintenance costs.

[0050] In addition, the network interface standardization module mainly includes two key parts in its implementation: unified network interface abstraction and network interface specification.

[0051] Unified Network Interface Abstraction: This module defines the unified operating logic required by various physical communication hardware and provides standard adapter implementation templates for different communication methods. For example, for 4G modules, a dialing and data transmission adapter based on the AT command set is configured to convert standard send / receive calls into specific AT commands (such as AT+QISEND). For WiFi modules, a TCP / IP stack adapter implemented via SPI / UART is configured to handle data frame encapsulation and parsing at the link layer. For Ethernet, a RAW Socket implementation based on the MAC layer driver is used to directly process Ethernet frame data. This design ensures that any physical connection uses a unified set of operations for the protocol stack.

[0052] Network Interface Specification: To achieve the unified network interface abstraction described above, the module defines a strict network adapter interface specification, as shown in the code below: typedef struct { int (*init)(void); / / Initialize network hardware int (*send)(const uint8_t *data, size_t len); / / Send data int (*recv)(uint8_t *buf, size_t max_len, uint32_t timeout); / / Receive data (timeout supported) } net_adapter_t; When the protocol stack needs to be ported to a new hardware platform or a new communication module needs to be used, developers only need to implement these three specific functions for that module according to this specification. For example, implement the `lte_send` function for a new 4G module, filling it with its unique AT commands. At runtime, the protocol stack holds and calls function pointers in the currently active `net_adapter_t` instance. After the TLS encryption module completes data encryption, it can directly call `adapter->send()` to send the ciphertext; it doesn't need to know whether the underlying data is being transmitted via 4G, WiFi, or Ethernet.

[0053] To enable rapid deployment and flexible adaptation of the lightweight TLS protocol stack of this invention in actual products, this invention provides a method for using the protocol stack. This method aims to standardize the complex protocol stack integration process, reducing the difficulty and development cycle of porting to various low-cost IoT devices. The following describes the method for using the lightweight TLS protocol stack of this invention: Step 1: Place the source code files of this protocol stack into the embedded project to be developed on the target device for porting.

[0054] The protocol stack provides a set of flexibly configurable header files or configuration files, including configuration of the static memory pool size, which includes related macro definitions such as xxx_SIZE to configure the memory pool and data buffer size, etc., which can be flexibly configured according to the actual resources of the microcontroller and provide a minimum limit; there is also related macro definition xxx_CNT to configure the maximum number of attempts in the TLS handshake process; related parameter configurations can be added and expanded as the protocol stack is upgraded.

[0055] Step 2: Interface compatibility adaptation.

[0056] Perform time synchronization (optional); implement an adapter for the selected network type; configure certificates (optional), placing the CA certificate or client certificate in the cert_pool area. Standardize the RTC interface, optionally porting the basic RTC functions for the corresponding hardware platform, providing the current accurate RTC time for protocol stack certificate authentication; the standardized network interface needs to be adapted to the corresponding underlying network's send / receive functions and specify the network type; the standardized certificate interface (optional) needs to contain a TLS certificate for connection handshake use, depending on the actual application.

[0057] Step 3: Interface integrity verification.

[0058] To check whether the standardized interface has been fully adapted, the protocol stack has a built-in multi-level interface integrity verification mechanism, including: Static checking layer: Compile-time macro definition checking: Forces verification of whether necessary interfaces are declared (such as NET_SEND_ENABLED) using the r instruction. Link-time symbol checking: Verifies the existence of critical functions (such as net_send()) in the final firmware using the linker script.

[0059] Dynamic testing layer: Self-tests during system startup. During the initialization phase, the protocol stack automatically traverses the interface list, including registered standardized interfaces (such as network adapters), and performs testing operations.

[0060] Error diagnosis: Provides an error code mapping table, allowing you to fix problems based on the corresponding error codes.

[0061] Step 4, Secure communication connection detection.

[0062] Using the standardized communication interface provided by the protocol stack, select the corresponding network type, test the connection to the TLS server, and send and receive data.

[0063] The processing flow of the above protocol stack usage method is as follows: Figure 2 As shown, the application scenarios after porting the lightweight TLS protocol stack of this invention are as follows: Figure 3 As shown.

[0064] The present invention also provides an Internet of Things (IoT) device configured with the lightweight TLS protocol stack described in the above embodiments.

[0065] It should be noted that the terms "comprising," "including," or any other variations thereof are intended to cover non-exclusive inclusion, such that a process, method, article, or apparatus that comprises a list of elements includes not only those elements but also other elements not expressly listed, or elements inherent to such a process, method, article, or apparatus. Without further limitation, an element defined by the phrase "comprising one..." does not exclude the presence of other identical elements in the process, method, article, or apparatus that includes said element.

[0066] The above description is only a preferred embodiment of the present invention. It should be noted that for those skilled in the art, several improvements and modifications can be made without departing from the technical principles of the present invention, and these improvements and modifications should also be considered within the scope of protection of the present invention.

Claims

1. A lightweight TLS protocol stack, characterized in that, include: The TLS encryption module is used for handshake negotiation with the peer, as well as for data encryption, decryption, and transmission management. A network interface standardization module is used to provide network adapters for different types of communication modules and to manage the communication modules through a unified interface specification. The TLS encryption module includes a random number entropy source logic component, which is used to selectively configure multiple delay lines with different lengths and paths to form a hardware entropy source array. The hardware entropy source array samples the random jitter generated by the pulse signal input to the delay line to obtain physical random bits. The physical random bits are used to generate random numbers required for handshake negotiation. The delay line is composed of logic gates and configurable I / O pins inside the device chip.

2. The lightweight TLS protocol stack according to claim 1, characterized in that, The TLS encryption module also includes a timestamp verification component, used to estimate a dynamic confidence window of the current time based on the relative time drift rate between the pre-acquired anchor time and the internal clock when verifying the validity of the peer certificate in the absence of an external time source, and to perform certificate validity verification based on the dynamic confidence window; wherein, the size of the dynamic confidence window is proportional to the elapsed time since the anchor time, and the relative time drift rate is calibrated by security heartbeat messages exchanged between devices.

3. The lightweight TLS protocol stack according to claim 1, characterized in that, The TLS encryption module also includes a cipher suite management component, used to adjust the priority order of cipher suites to be negotiated during handshake negotiation with the peer according to the current operating status of the device. The operating status includes at least one of battery level, CPU load, or network threat level. When the battery level is lower than a preset threshold, the priority of cipher suites supported by the hardware accelerator is increased. The negotiated cipher suites are used to generate the session master key.

4. The lightweight TLS protocol stack according to claim 3, characterized in that, The TLS encryption module also includes a handshake management component, which generates a preliminary master key during handshake negotiation and stores the preliminary master key in a pre-allocated static memory pool. A hash operation is performed on the data in the static memory area where the preliminary master key is stored in the static memory pool to obtain the corresponding hash value; the hash value is compared with the expected value derived from the preliminary master key, and the handshake connection is terminated if the comparison result does not match; wherein, the preliminary master key and the random number are used as input data when generating the session master key from the negotiated cipher suite.

5. The lightweight TLS protocol stack according to claim 4, characterized in that, The handshake management component is also used to verify, upon receiving a session recovery request from the peer, whether the secondary credential carried in the session recovery request is derived from the master key of the previous session; if so, the session recovery request is approved.

6. The lightweight TLS protocol stack according to claim 1, characterized in that, The TLS encryption module also includes a data transmission and reception management component, which is used to set up multiple data priority queues for the pre-configured transmit ring buffer and receive ring buffer when encrypting, decrypting and managing the transmission of data. The priority of the multiple data priority queues is determined by weighting the predefined priority of the data type stored therein; and the data blocks in the multiple data priority queues are scheduled and processed by a weighted round-robin scheduler.

7. The lightweight TLS protocol stack according to claim 6, characterized in that, When the data transceiver management component performs encryption, decryption, and transmission management on the data, it is also used to identify the fixed header portion of the application layer protocol message with a known fixed format in the application layer data before the application layer data enters the transmission ring buffer, perform pre-encryption processing on the fixed header portion, and store the pre-encryption result; when sending the application layer protocol message, it encrypts the variable payload portion of the application layer protocol message, and concatenates the pre-encryption result with the encrypted variable payload portion before sending.

8. The lightweight TLS protocol stack according to claim 1, characterized in that, The TLS encryption module also includes a certificate verification component, which caches the hash values ​​of the peer certificate and the CA certificates in its verification path after successful verification of the peer certificate, in order to form a fingerprint chain.

9. The lightweight TLS protocol stack according to claim 8, characterized in that, The certificate verification component is also used to compare the CA certificate hash value embedded in the peer certificate with the locally cached fingerprint chain when verifying the peer certificate if the peer's CA certificate cannot be downloaded; if a fingerprint chain that can be traced back to a locally preset trusted root certificate is found, a communication connection is established with the peer; the communication connection is marked as a cache-verified connection, and the peer's access permissions are restricted to allow only data reporting.

10. An Internet of Things (IoT) device, characterized in that, The IoT device is configured with the lightweight TLS protocol stack as described in any one of claims 1-9.