A modbus TCP protocol lightweight encryption method based on SM4 and SM3 of national secret

CN122802187APending Publication Date: 2026-09-22WUHAN UNIV
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202610783950.9
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-06-02
Publication Date
2026-09-22

AI Technical Summary

Technical Problem

[0004]现有的安全加固方案主要分为三类:第一类为传输层安全协议(TLS/DTLS)方案,通过在传输层叠加TLS握手与AES-GCM全包加密来实现端到端安全,但TLS握手延迟与全包AES加密的CPU开销对于主频仅有几十至数百MHz、RAM资源仅有数十KB的典型工控嵌入式节点,如Siemens S7-1200等而言难以承受,且多数老旧工控设备不支持TLS协议栈的升级部署

Benefits of technology

(1)高效性:通过关键字节选择性加密策略,将SM4单次加密的数据量由原始报文全量,其平均为15至60字节,压缩至固定16字节,加密耗时与报文长度完全解耦,消除了报文长度变化对加密延迟的不确定性影响。在五个公开工控流量数据集(Morris_ICS_Dataset、Quickdraw-PCAP、OpenICS-PCAP、BATADAL及CIC_Modbus)的流量子集上,本方案总处理时间相比AES-256-CBC全包加密基线方案减少65%以上,系统吞吐量约为基线方案的2.88至3.11倍。

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122802187A_ABST
    Figure CN122802187A_ABST
Patent Text Reader

Abstract

The application discloses a kind of Modbus TCP protocol light-weight encryption methods based on SM4 and SM3 of national secret.The method is in view of the problem that the encryption delay is high and real-time is poor due to the limited computing resources of industrial node, a kind of key byte encryption strategy is proposed, that is, only the function code and register address in Modbus PDU are extracted as key bytes, and encrypted by SM4 algorithm;At the same time, for the integrity check requirement, a sparse hash chain mechanism based on SM3 algorithm is designed, only for the check of write operation, and set to update the hash seed every N operation, and the current hash is reused for the rest operation.For high-frequency read operation, a zero-integrity-overhead fast path is used.Experimental data shows that the application significantly reduces the hash calculation frequency while ensuring compliance with national secret, and the system processing efficiency is improved by more than 65% on synthetic data set, and by 69.6% to 80.3% on five public industrial PCAP data sets.The application is suitable for industrial data acquisition and control scenarios with extremely high real-time requirements.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of information security technology for Industrial Control Systems (ICS), specifically to a lightweight encryption method for the Modbus TCP protocol based on the national standard SM4 block encryption algorithm and the SM3 cryptographic hash algorithm. This invention significantly reduces the encryption and decryption computational overhead of embedded industrial control nodes while ensuring compliance with national standard cryptographic protocols and the real-time performance of industrial control systems through selective encryption of key fields, hierarchical processing of operation types, and a sparse hash chain integrity verification mechanism. It is suitable for secure communication scenarios of industrial control terminal devices such as PLCs, RTUs, and sensors with limited computing resources. Background Technology

[0002] With its simple structure, low implementation cost, and strong cross-platform compatibility, the Modbus protocol has become one of the most widely deployed fieldbus communication protocols in the field of industrial automation. The Modbus TCP variant, based on TCP / IP networks, further expands the application scope of this protocol to critical infrastructure scenarios such as the Industrial Internet of Things, smart grids, oil and gas pipeline SCADA systems, and urban water supply automation control, and has a large number of online nodes in industrial control networks worldwide.

[0003] However, the Modbus protocol was initially designed primarily for closed, trusted fieldbus physical network environments, lacking any built-in security mechanisms: message data is transmitted in plaintext, and the protocol layer does not provide any authentication, message integrity protection, or data encryption. With the deep integration of industrial control systems with enterprise IT networks and the internet, the originally physically isolated industrial control networks are exposed to attack threats from external networks. Typical attack methods against Modbus TCP include: network sniffing, such as eavesdropping on plaintext control commands and sensor data; man-in-the-middle attacks; control command replay attacks; and denial-of-service attacks. According to publicly available research statistics in the field of industrial control system security, a significant proportion of disclosed industrial control system network attack incidents involve the malicious exploitation of mainstream industrial control protocols such as Modbus, including both abusing inherent security flaws in the protocols and exploiting related security vulnerabilities.

[0004] Existing security hardening solutions mainly fall into three categories: The first category is Transport Layer Security (TLS / DTLS) solutions, which achieve end-to-end security by overlaying TLS handshakes and AES-GCM full-packet encryption at the transport layer. However, the TLS handshake latency and the CPU overhead of full-packet AES encryption are unbearable for typical industrial control embedded nodes with clock speeds of only tens to hundreds of MHz and RAM resources of only tens of KB, such as the Siemens S7-1200. Furthermore, most older industrial control equipment does not support the upgrade and deployment of the TLS protocol stack. The second category is Virtual Private Network (VPN) solutions, which protect industrial control communications by implementing encrypted tunnels at the network layer. However, the centralized traffic redirection method of VPN gateways introduces additional single-point-of-failure risks, and the deployment of IPSec protocol stacks at the industrial control end nodes is also unfriendly to resource-constrained devices. The third category is application layer gateway proxy solutions, which encrypt and decrypt Modbus traffic by deploying secure proxy devices at the industrial control network boundary. However, the proxy devices become new security and performance bottlenecks, and the additional latency introduced by transparent proxy forwarding is unacceptable in high real-time scenarios, such as power grid relay protection and robot motion control.

[0005] All the above schemes share a common flaw: they perform full encryption on Modbus TCP packets. However, the critical fields carrying control semantics (function code + register address) in Modbus TCP packets only account for about 20% to 35% of the total packet length, with the remainder being non-sensitive numerical payloads. This full encryption strategy results in the amount of encrypted data far exceeding the minimum necessary range for security, leading to a significant waste of computational resources.

[0006] Meanwhile, with the advancement of national cryptographic compliance policies such as the "Administrative Measures for Commercial Cryptographic Application and Security Assessment," industrial control systems involving critical information infrastructure are explicitly required to adopt national cryptographic algorithms (SM2 / SM3 / SM4) recognized by the State Cryptography Administration to replace internationally used algorithms such as RSA, AES, and SHA. How to construct a lightweight Modbus TCP security solution that balances national cryptographic compliance and real-time requirements under the current computing power constraints of embedded industrial control equipment has become a critical technical problem that urgently needs to be solved in the field of industrial security. Summary of the Invention

[0007] The purpose of this invention is to provide a lightweight encryption method for the Modbus TCP protocol based on the national cryptographic standards SM4 and SM3. Under the condition of limited computing resources in embedded industrial control nodes, it can achieve encryption protection, integrity verification and replay detection of Modbus TCP communication with significantly lower computational overhead than the full-packet encryption scheme, while meeting the national cryptographic compliance requirements throughout the process.

[0008] According to one aspect of this invention, a lightweight encryption method for the Modbus TCP protocol based on the national cryptographic standards SM4 and SM3 is provided, comprising: parsing the original Modbus TCP message, extracting the function code and register address from the protocol data unit (PDU) as key byte codes; encrypting the key byte codes using the national cryptographic standard SM4 algorithm to generate a fixed-length encrypted block and replace the corresponding fields in the original message; determining the operation type of the current message based on the function code and executing a hierarchical processing path: if it is a read operation, a fast path is used, and the encrypted message is directly sent to the data acquisition end without performing integrity verification; if it is a write operation, a sparse hash chain verification mechanism based on the national cryptographic standard SM3 algorithm is triggered; the sparse hash chain verification mechanism calculates the integrity verification value (ICV) according to a preset update step size N, and embeds the ICV at the end of the message with the data transmission.

[0009] As a further technical solution, the keyword bytecode is formed by concatenating a 1-byte function code with a 2-byte start register address.

[0010] As a further technical solution, the key bytecode is encrypted using the national cryptographic SM4 algorithm. Specifically, the 3-byte key bytecode is padded with a 2-byte sequence number (big-endian) and 11 bytes of fixed padding to a total of 16 bytes. This is then encrypted using a preset key in the ECB mode of the SM4 algorithm. This solution sets the 13-byte padding to "2-byte sequence number seq_bytes (big-endian) + 11-byte fixed padding 0x0B", ensuring the uniqueness of each plaintext block and eliminating the attack surface for traffic analysis.

[0011] As a further technical solution, the scope of the write operation includes function codes 0x05, 0x06, 0x0F and 0x10; the read operation is an operation other than the scope of the write operation.

[0012] As a further technical solution, the sparse hash chain verification mechanism specifically includes: the system maintains a global counter and a current hash state value; whenever a write operation message is captured, the global counter is incremented; when the global counter is less than the update step size N, the current hash state value is directly assigned to the ICV of the current message; when the global counter is greater than or equal to the update step size N, the SM3 algorithm is used to perform a hash operation on the current hash state value and the key bytecode of the current message, update the current hash state value and clear the global counter.

[0013] As a further technical solution, the update step size N is a configurable parameter; the ICV is 8 bytes, and for read operations, the ICV is filled with 8 bytes of all zeros.

[0014] As a further technical solution, the method also includes a message reassembly process: retaining the original MBAP header, sequentially concatenating the 16-byte SM4 ciphertext, the 8-byte ICV checksum, and the remaining data payload in the original message, and synchronously modifying the length field in the MBAP header according to the total length after concatenation.

[0015] According to one aspect of the present invention, a lightweight data encryption acquisition system for implementing the method is provided, comprising: a message parsing unit, used to parse Modbus TCP raw messages and extract function codes and register addresses from Protocol Data Units (PDUs) as key byte codes; an SM4 encryption unit, used to encrypt the key byte codes using the national cryptographic SM4 algorithm to generate a fixed-length encryption block; a logic distribution unit, used to determine the operation type of the current message based on the function code, distinguish read and write paths, and maintain the state of a sparse hash counter; and an SM3 verification unit, used to trigger a sparse hash chain verification mechanism based on the national cryptographic SM3 algorithm when a write operation is determined, and calculate an integrity verification value (ICV) based on a preset update step size N.

[0016] According to one aspect of the present invention, a transmitting device is provided, comprising: a memory for storing a computer program; and a processor, wherein when the processor executes the computer program, it implements the steps of the transmitting end in the method, the steps including: parsing a Modbus TCP packet to be transmitted, extracting a key byte and performing SM4 encryption; determining whether to trigger SM3 sparse hash chain calculation to generate an ICV based on the operation type; embedding the encrypted block and the ICV into the original packet, reassembling and transmitting the encrypted packet.

[0017] According to one aspect of the present invention, a receiving device is provided, comprising: a memory for storing a computer program; and a processor, wherein when the processor executes the computer program, it performs the following steps: receiving an encrypted message, extracting an SM4 ciphertext block for decryption to restore the key byte; extracting ICV and performing integrity verification on a write operation message based on a locally maintained hash chain state and an update step size N; and reassembling the original Modbus TCP message after the verification passes.

[0018] Compared with the prior art, the beneficial effects of the present invention are as follows: (1) High efficiency: By using a key byte selective encryption strategy, the amount of data encrypted in a single SM4 packet is compressed from the original full packet, which averages 15 to 60 bytes, to a fixed 16 bytes. The encryption time is completely decoupled from the packet length, eliminating the uncertainty of encryption latency caused by changes in packet length. On traffic subsets of five publicly available industrial control traffic datasets (Morris_ICS_Dataset, Quickdraw-PCAP, OpenICS-PCAP, BATADAL, and CIC_Modbus), the total processing time of this solution is reduced by more than 65% compared to the AES-256-CBC full packet encryption baseline solution, and the system throughput is approximately 2.88 to 3.11 times that of the baseline solution.

[0019] (2) Low hash overhead: The sparse hash chain mechanism reduces the SM3 hash calculation frequency from once per write operation (dense scheme) to once per N write operations. In mixed read and write traffic scenarios, the number of SM3 function calls is reduced by about 90% in actual tests on synthetic datasets compared to traditional dense schemes, and by 94% to 97% in actual tests on five public industrial control PCAP datasets. This significantly reduces the CPU utilization of embedded industrial control nodes and ensures the millisecond-level real-time requirements of industrial control systems.

[0020] (3) Full compliance with national cryptographic standards: This invention adopts commercial cryptographic algorithms recognized by the State Cryptography Administration throughout the process: SM4 (GB / T32907-2016) for data encryption and SM3 (GB / T 32905-2016) for integrity verification, which meets the national cryptographic compliance requirements of the "Administrative Measures for Security Assessment of Commercial Cryptographic Applications" and key information infrastructure, and is applicable to the application and certification of cryptographic products in the industrial control field.

[0021] (4) Protocol backward compatibility: This invention is implemented at the Modbus TCP application layer, retaining the original fields such as transaction ID, protocol ID, and unit ID in the MBAP header, without modifying the underlying transmission protocol frame format. It can be incrementally deployed to existing industrial control systems through middleware or firmware updates without replacing the existing Modbus TCP protocol stack, thus minimizing the transformation cost.

[0022] (5) Adjustable security strength: The update step size N of the sparse hash chain supports dynamic configuration. The smaller N is, the more frequent the hash update and the stronger the integrity protection, but the greater the computational overhead. The larger N is, the less frequent the hash update and the stronger the integrity protection. Operators can flexibly achieve the optimal balance between security strength and real-time performance according to the security level requirements of specific industrial control scenarios and the computing power constraints of embedded nodes, thereby improving the engineering adaptability of the solution.

[0023] (6) Anti-replay capability: The dual binding mechanism of sequence number and hash chain depth ensures the uniqueness of each legitimate message in time sequence. After an attacker intercepts and retransmits any historical message, the receiving end can quickly detect and discard it by the discontinuous sequence number or inconsistent hash chain state, effectively preventing device state manipulation attacks implemented by replaying write operation messages. Attached Figure Description

[0024] To more clearly illustrate the technical solutions in the embodiments of the present invention or the prior art, the accompanying drawings used in the description of the embodiments or the prior art will be briefly introduced below. Obviously, the accompanying drawings described below are some embodiments of the present invention. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.

[0025] Figure 1 This is a schematic diagram of the overall process of the lightweight encryption method provided in the embodiments of the present invention, which shows the complete processing flow from the input of the original Modbus TCP packet to the output of the encrypted packet, including operation type classification and determination, SM4 key byte encryption path, sparse hash chain update path, fast read path and final packet assembly structure.

[0026] Figure 2 The graph shows a comparison of the total processing time of the lightweight solution and the baseline solution provided in this embodiment of the invention with different sizes of randomly generated datasets. The horizontal axis represents the number of data packets, and the vertical axis represents the total processing time.

[0027] Figure 3 The bar chart compares the percentage performance improvement of the lightweight solution provided in this embodiment of the invention with the baseline solution on six public / synthetic datasets. The horizontal axis represents the source of each dataset, and the vertical axis represents the percentage performance improvement (%). The red dashed line marks the 40% target threshold.

[0028] Figure 4 The line graph comparing the system throughput (data packets / second) of the lightweight solution and the baseline solution provided in this embodiment of the invention under different dataset sizes demonstrates the throughput advantage of this solution in high-load scenarios.

[0029] Figure 5 The bar chart comparing the number of SM3 hash calculations between the sparse hash chain provided in this embodiment of the invention and the baseline dense hash scheme under different dataset sizes, along with the corresponding statistical chart of the reduction in hash calculations, demonstrate the computational saving effect of the sparse strategy.

[0030] Figure 6 The bar chart comparing the increase in encrypted data packet size (data overhead percentage) between the lightweight solution provided in this embodiment and the baseline solution demonstrates the advantage of this solution in terms of bandwidth utilization efficiency.

[0031] Figure 7 This is a comparison chart of the decomposition and stacking of encryption and decryption times in the encryption scheme provided in the embodiments of the present invention, showing the composition ratio of encryption and decryption time for the lightweight scheme and the baseline scheme under different dataset sizes.

[0032] Figure 8 This is a comprehensive comparison chart of the performance improvement and stability analysis on five publicly available industrial control traffic datasets provided in the embodiments of the present invention. The horizontal axis represents the identifier of each dataset or subset, and the vertical axis represents the performance improvement ratio (%). It shows the performance robustness of the present invention under different industrial control protocol scenarios, attack types and device topology conditions. The dashed line marks the overall average performance improvement value of all subsets. Detailed Implementation

[0033] The terms “comprising” and “having”, and any variations thereof, in the specification, claims, and accompanying drawings of this invention are intended to cover a non-exclusive inclusion, such as a process, method, system, product, or apparatus that includes a series of steps or units, not necessarily limited to those explicitly listed, but may include other steps or units not explicitly listed or inherent to such processes, methods, products, or apparatus.

[0034] To make the objectives, technical solutions, and advantages of the embodiments of the present invention clearer, the technical solutions of the embodiments of the present invention will be clearly and completely described below in conjunction with experiments on publicly available industrial control traffic datasets and specific logical implementations, as well as the accompanying drawings. Obviously, the described embodiments are only a part of the embodiments of the present invention, not all of them. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention. Furthermore, the technical features of the various embodiments or individual embodiments provided by the present invention can be arbitrarily combined to form new technical solutions. Such combinations are not constrained by the order of steps and / or structural composition patterns, but must be based on the ability of those skilled in the art to implement them. When the combination of technical solutions is contradictory or cannot be implemented, it should be considered that such a combination of technical solutions does not exist and is not within the scope of protection claimed by the present invention.

[0035] See Figure 1 The present invention provides a lightweight encryption method for Modbus TCP protocol based on Chinese national cryptographic algorithms, and the specific implementation process is as follows.

[0036] 1. Modbus Keyword Extraction and SM4 Encryption: This invention does not encrypt the entire data in Modbus TCP packets. Instead, it extracts semantically sensitive key fields from Protocol Data Units (PDUs) as encryption objects. Specifically, the Function Code (1 byte) and the starting register address (2 bytes), totaling 3 bytes, are defined as a "keyword block." This block is padded to the SM4 packet size (16 bytes) using fixed-byte padding. The padded block is then encrypted using the ECB mode of the Chinese national cryptographic SM4 algorithm, generating a 16-byte ciphertext block embedded in the packet. These 3 bytes carry the operation type and target address of the Modbus control instruction and are the most semantically sensitive core part of the instruction, constituting the minimum necessary object for encryption protection in this invention. For register value payloads, due to their relatively low security sensitivity and the fact that they typically have value range constraints at the application layer, this invention adopts a transparent transmission strategy, not encrypting this part. This significantly reduces the data volume of a single SM4 operation and lowers the encryption / decryption time for each data packet.

[0037] As one implementation method, the Modbus TCP packet structure and key field definitions are as follows:

[0038] This embodiment defines the memory representation structure of a standard Modbus TCP packet using the ModbusTCPPacket class. A Modbus TCP packet consists of a 7-byte MBAP header and a variable-length PDU, with the following specific fields: MBAP header: Transaction ID (2 bytes, big-endian, incremented by the master station, used for request-response pairing); Protocol ID (2 bytes, fixed at 0x0000, identifies the Modbus protocol); Length (2 bytes, representing the number of subsequent bytes, equal to the number of PDU bytes plus 1); Unit ID (1 byte, slave address).

[0039] PDU: Function Code (1 byte, identifies the operation type, such as 0x03 for reading holding registers, 0x10 for writing multiple registers); Data field (variable length, which may include fields such as starting address, quantity, and value depending on the function code).

[0040] The lightweight encrypted Modbus TCP packet structure defined in this invention is shown in Table 1.

[0041] Table 1 Lightweight Encrypted Modbus TCP Packet Structure .

[0042] 2. Integrity verification mechanism triggered by write operations: For read operations (function code 0x01 read coil, 0x02 read discrete input, 0x03 read holding register, 0x04 read input register, etc.), a "fast path" is adopted: only SM4 key byte encryption is performed, the 8-byte integrity check field in the message is filled with all zeros, and SM3 hash calculation is not triggered, thus minimizing the processing latency of read operations. In industrial control scenarios, read operations typically account for 60% to 80% of the total communication volume, and this optimization has a significant effect on improving overall throughput. For write operations (function code 0x05 write single coil, 0x06 write single register, 0x0F write multiple coils, 0x10 write multiple registers), since these involve changes to the state of the controlled device's registers, they are considered high-risk operations. Therefore, an integrity check value (ICV) based on an SM3 sparse hash chain needs to be added to the SM4 encryption to prevent instruction tampering and replay attacks.

[0043] As one implementation method, SM4 key byte encryption and message assembly are as follows: The lightweight encryption module pre-creates SM4 encryption and decryption context objects during system initialization and pre-calculates the round key corresponding to the 16-byte SM4 key, avoiding repeated key expansion in high-frequency encryption call paths. It also pre-allocates 13 bytes of fixed padding constants and 8 bytes of zero constants to eliminate dynamic memory allocation overhead in high-frequency call paths.

[0044] The encryption process is performed according to the following steps: Step A: The global sequence counter (sequence) performs an atomic increment operation to assign a unique sequence number to this encrypted message and writes the sequence to the MBAP transaction ID field (transaction_id). This field is reused to carry the anti-replay sequence number without the need to add new bytes.

[0045] Step B: Read the PDU function code, determine if it belongs to the write operation set W = {0x05, 0x06, 0x0F, 0x10}, and set the boolean flag is_write. The read operation set is defined as R = {0x01, 0x02, 0x03, 0x04}.

[0046] Step C: When the PDU data field length is ≥2 bytes, extract the starting address and the remaining payload. Concatenate the function code and the starting address to form a 3-byte key block critical_bytes, add 13 bytes of fixed padding to form a 16-byte plaintext block P, and call the pre-created SM4 encryption context to encrypt P in ECB mode, generating a 16-byte ciphertext block C = SM4_ECB_ENC (key, P).

[0047] Step D: If `is_write` is false, ICV is directly assigned an 8-byte zero vector, skipping the hash chain module and proceeding to step E; if `is_write` is true, the `should_update()` method of the sparse hash chain module is called. Internally, `pending_count` is incremented by 1. If `pending_count` ≥ N, `pending_count` is reset to 0 and `True` is returned; otherwise, `skipped_updates` is incremented by 1 and `False` is returned. When an update is triggered, `update(critical_bytes)` is called to perform hash chain iteration and return a new 8-byte truncated value as ICV; when an update is skipped, `get_current()` is called to return the current hash chain state value as ICV.

[0048] Step E: According to the encrypted message structure defined in this invention, sequentially write the MBAP transaction ID (also serving as the sequence number seq, written in step A), protocol ID, length field, unit ID, SM4 ciphertext block C, ICV, and remaining_data to generate the final encrypted message byte string. The receiving end extracts seq_recv from this field to complete replay detection.

[0049] The decryption process is performed as follows: Extract each field from the received message by offset; take the 16-byte SM4 ciphertext block at byte offsets 7 to 22, decrypt it in ECB mode using the pre-created SM4 decryption context to obtain a 16-byte plaintext block; read the last byte of the plaintext block as the padding length `padding_len`, remove the padding data in the suffix `padding_len` bytes, and restore the 3-byte key byte group; concatenate the restored key byte group with the register value payload at the end of the message to reconstruct the complete Modbus TCP packet PDU, and recover the fields of the MBAP header from the message header to generate a complete original ModbusTCPPacket object to return to the upper layer application. If the function code belongs to the write operation set, the following two steps must also be performed: (a) Extract the 8-byte ICV field at the offset of byte 23 to 30 of the message and compare it with the locally maintained hash chain state H_local. If they are inconsistent, discard the message and issue an alarm; (b) After the verification is passed, increment the local counter pending_local according to the same step size strategy as the sender. When pending_local reaches the step size threshold N, perform SM3 iterative update of H_local and clear the counter to ensure that the hash chain state of the receiver and the sender is always synchronized.

[0050] 3. Sparse hash chain update strategy:

[0051] To further reduce the computational overhead of SM3, this invention designs a sparse update mechanism. By presetting the update step size N, a new hash seed is calculated only when the step size condition is met, and intermediate packets share the previous hash state value. The hash chain update formula is: , Among them New hash chain truncation value, The truncation value for the current hash chain. This is the key group for the write operation that triggered the update. "+" indicates a byte string concatenation operation. SM3 is the SM3 cryptographic hash function, which outputs a 32-byte hash value. The first 8 bytes are taken as the new hash chain truncation value. .

[0052] The design of this formula reflects the unidirectional chaining dependency of the hash chain: each update retrieves the chain state from the previous round. Semantic information related to this write operation Together they serve as the input to SM3, making It simultaneously binds the historical chain state with the current operation content. On the one hand, the one-way nature of SM3 ensures that attackers cannot... Reverse push Therefore, it is impossible to forge historical chain states; on the other hand... The mixing of different write operation sequences results in different hash chain paths. Any replacement or rearrangement of the write operation message will cause the chain value recalculated at the receiving end to be inconsistent with the ICV carried in the message, thus being detected as tampering. The sparse update strategy stipulates that the above formula iteration is only executed once when the counter to be updated accumulates to the step size threshold N. The remaining intermediate write operation messages reuse the current... As an ICV, it maintains the integrity protection capability of the hash chain while reducing the SM3 calculation frequency to 1 / N.

[0053] Furthermore, the ICV field is assigned according to the following strategy: When a write operation triggers a hash chain update, ICV = This refers to the new hash chain truncation value after this update; When a write operation does not trigger a hash chain update, ICV = This means reusing the previous update result without re-executing the SM3 operation; When it is a read operation, ICV = 0x0000000000000000, which does not carry integrity verification information, saving SM3 computation overhead.

[0054] As one implementation method, the initialization and state management of the sparse hash chain are as follows: The sparse hash chain module is initialized during instantiation using the following steps: a 16-byte random seed `initial_seed` is generated using the operating system's cryptographically secure random number generator; an SM3 hash operation is performed on `initial_seed` to obtain a 32-byte hash value; the first 8 bytes of this hash value are taken as the initial hash chain state to complete the initial state setting; and the update interval `update_interval`, the pending update counter `pending_count`, the total number of updates `total_updates`, and the total number of skipped updates `skipped_updates` are initialized.

[0055] The state management methods are described as follows: The `should_update()` method increments `pending_count` by 1 each time it is called. It compares `pending_count` with the threshold `update_interval` to determine whether to trigger a hash chain update. This method is designed with idempotent and side-effect-free logic. The `update(data)` method performs a single-step iteration of the hash chain: it concatenates `current_hash` with the passed `critical_bytes` byte string in sequence as input to the `SM3` function, takes the first 8 bytes of the `SM3` output to update `current_hash`, increments the `total_updates` count by 1, and returns the new hash chain truncation value for filling the message's ICV field. The `get_current()` method directly returns the current `current_hash` value, allowing write operation messages that have not triggered an update to reuse the current hash state as their ICV, without additional hash calculation overhead.

[0056] Security analysis of the step size parameter N: A smaller N results in more frequent hash chain updates, and write operation packets between adjacent updates share the same ICV value. Attackers have a higher probability of not detecting packet tampering within this range due to ICV changes. A larger N results in lower hash computation overhead, but reduced security. When deploying a project, it is recommended to consider the following factors when selecting the N value: available computing power of the embedded node; the proportion of Modbus write operations in the total communication volume; and the target security level.

[0057] 4. Serial number mechanism to resist replay attacks: This invention assigns a monotonically increasing global sequence number to each encrypted message (carried by reusing the MBAP transaction ID field, monotonically increasing and periodically wrapping within a 2-byte space, jointly determined by the hash chain state). The sequence number is deeply bound to the hash chain, ensuring a one-to-one correspondence between the message set and the sequence number range within the same hash chain state. By verifying the continuity of the sequence number and the consistency of the hash chain state, the receiving end can effectively detect and reject replay attack messages, preventing attackers from manipulating the device by intercepting legitimate write operation messages and retransmitting them. Simultaneously, comparing the message integrity verification value (ICV) can further detect tampering attempts against messages in transit, achieving dual protection.

[0058] To objectively quantify the performance advantages of the lightweight solution of this invention, this embodiment simultaneously implements a baseline full-packet encryption scheme as a performance comparison benchmark: This scheme uses AES-256-CBC mode to encrypt the complete Modbus TCP packet, uses a randomly generated 16-byte IV to ensure semantic security, and performs 16-byte alignment padding on the packet according to the PKCS#7 specification; simultaneously, it performs a complete SM3 hash chain update separately for each data packet to maximize the SM3 computational overhead. The packet structure after encryption using the baseline scheme is: 16-byte random IV + aligned-padded AES ciphertext + 8-byte SM3 hash chain truncation value, with the total size increasing by approximately 48 to 64 bytes compared to the original packet, depending on the original packet length. This scheme represents the performance benchmark of the traditional "full AES encryption + dense SM3 HMAC" scheme, forming a direct comparison with this invention, such as... Figure 7 As shown.

[0059] To verify the performance of the proposed solution under real industrial control network traffic conditions, this embodiment introduces five publicly available industrial control traffic PCAP datasets and one synthetic control dataset for systematic experimental evaluation, covering various industrial control scenarios such as water SCADA, substation Modbus, liquid pump process automation, SCADA-PLC communication, and sensor filter testing. The datasets used are detailed below: (1) Coimbra_CyberSec_team Liquid Pump Process Automation Dataset: Collected and released by the cybersecurity team of the University of Coimbra, Portugal, it contains PLC-RTU horizontal communication Modbus TCP flow PAP files for liquid pump industrial control systems, covering typical process automation scenarios such as level sensor polling, pump control commands, and Arduino potentiometer temperature simulation.

[0060] (2) Quickdraw-PCAP Fast Draw Dataset: Quickdraw is a signature-based intrusion detection rule verification dataset designed for industrial control systems, containing test PCAP traffic for sensor communication filters. The Modbus TCP packets in this dataset cover various sensor polling and control command sequences, with high read operation density and strong packet structure regularity, making it suitable for verifying the fast path optimization effect of the present invention in high-frequency read polling scenarios.

[0061] (3) OpenICS-PCAP Public Industrial Control Traffic Capture Set: Modbus TCP raw traffic PCAP files collected in an isolated network environment based on the SCADA / ICS experimental platform. It contains complete communication sequences of various function code messages under typical industrial control operation scenarios and is an important data source for verifying protocol compatibility and comprehensive function code coverage.

[0062] (4) BATADAL Water SCADA Dataset: A water distribution network SCADA system dataset released by the BATADAL competition organizers, containing normal operation traffic based on the Modbus / TCP protocol and labeled traffic from various network attacks. The related PCAP files cover SCADA-PLC communication sequences under real water infrastructure topologies. This dataset is generated based on a real hydraulic model and includes Modbus read / write operations of various devices such as pressure sensors and flow meters, making it suitable for evaluating the practicality of the proposed solution in critical infrastructure protection scenarios.

[0063] (5) CIC Modbus Substation Dataset: The CIC Modbus dataset for simulated substation networks, released by the Canadian Cyber ​​Security Institute, contains network (PCAP) capture and attack logs from simulated substation network environments. It is divided into two categories: attack datasets and benign datasets. The benign dataset records Modbus polling and control command traffic between PLCs and RTUs under normal substation operation; the attack dataset covers various network attack scenarios targeting substations. This dataset is an important benchmark for verifying the applicability of the proposed solution in the field of power infrastructure industrial control protocol security.

[0064] (6) Synthetic control dataset: Random Modbus TCP packet sequences generated by the DatasetGenerator module according to the statistical characteristics of real industrial control scenarios are used to establish a benchmark performance reference under completely controllable conditions and to cross-validate with the experimental results of the public dataset.

[0065] A unified data preprocessing workflow is implemented: The Scapy network packet analysis library is used to parse PCAP files from various sources, extracting byte streams from the TCP layer Raw payload; validity filtering is performed according to the Modbus TCP packet format specification (MBAP header at least 8 bytes, length field consistent with the actual payload), discarding packets that are not in Modbus TCP format, have abnormal lengths, or fail the MBAP check; filtered packets are parsed using ModbusTCPPacket.from_bytes() to restore the function code and data fields; the maximum number of valid packets extracted from each PCAP file is set to 10,000, with any exceeding this limit truncated. Statistics on valid Modbus TCP packets for each dataset are shown in Table 2.

[0066] Table 2. Statistics of valid messages between five publicly available industrial control PCAP datasets and a synthetic control set. .

[0067] The results of the comparative experimental design and performance verification are as follows:

[0068] A systematic comparative experiment was conducted between the lightweight scheme of this invention and the baseline scheme using the ExperimentRunner class. The experiment was performed on an x86-64 architecture Windows platform (Python 3.10, gmssl 0.2.2, PyCryptodome 3.20.0). The test dataset sizes covered 100, 500, 1000, 3000, 5000, and 10000 data packets. For each size, the test was repeated three times on the same subset of data, and the average value was taken to eliminate timing jitter errors. As shown in Table 3, the experimental measurement indicators included: encryption time (encryption stage only), decryption time (decryption stage only), total processing time (encryption + decryption), number of SM3 hash updates, system throughput (data packets / second), and the data packet size expansion rate after encryption (%).

[0069] Table 3. Comparison of experimental results between the lightweight scheme and the baseline scheme on the synthetic control dataset. .

[0070] Note: LW = Lightweight Scheme (SM4 byte encryption + sparse SM3 hash chain, step size N=5); BL = Baseline Scheme (AES-256-CBC full packet encryption + dense SM3 packet-by-packet update). Packet size growth rate: LW scheme approximately 117.7% to 123.6%, BL scheme approximately 162.2% to 169.3% (see details). Figure 6 ).

[0071] Table 4. Comparison of experimental results between the lightweight scheme and the baseline scheme on five publicly available industrial control PCAP datasets. .

[0072] (1) Scalability of synthetic datasets Based on the full-scale gradient test results of the synthetic control dataset (packets 100 to 10000) in Table 3, the total processing time of the lightweight solution remained stable between 31.6% and 34.7% of the baseline solution, corresponding to a stable performance improvement of 65.3% to 68.4%, with no significant performance degradation, demonstrating excellent linear scalability. Figure 2 As shown, the throughput of the lightweight solution is stable in the range of 8139 to 8599 packets / second, while the throughput of the baseline solution is stable in the range of 2766 to 2853 packets / second. The throughput of the lightweight solution is 2.88 to 3.11 times that of the baseline solution, which fully verifies the consistent efficiency of the proposed solution under different communication data scales. Figure 4 As shown.

[0073] (2) Saving effect of SM3 hash calculation In full-scale testing on the synthetic control dataset, the lightweight solution consistently reduced the number of SM3 hash calls by 90.0% to 90.3%. In tests on five publicly available industrial control PCAP datasets, the hash reduction further improved to 94.0% to 97.0%, with both test results significantly outperforming the theoretical expectation of 80% in pure write operation scenarios. This theoretical value was calculated based on a step size of N=5. In pure write operation scenarios, hash updates are optimized from per-packet execution to once every 5 packets, corresponding to a theoretical hash saving of 80%. The synthetic dataset used in this test had an actual read-to-write ratio of approximately 1:1. The baseline solution performed per-packet SM3 hash updates for both reading and writing full data packets. The lightweight solution of this invention completely skips SM3 hash calculations for read operations, only performing hash chain updates at a frequency of 1 / 5 for write operations. The overall hash saving ratio is significantly higher than the theoretical value in pure write operation scenarios, quantitatively verifying the actual optimization effect of the sparse hash chain mechanism under mixed read-write industrial control traffic. Figure 5 As shown.

[0074] (3) Improved performance across datasets Table 4 shows the test results, indicating that the measured performance improvement of the five publicly available industrial control PCAP datasets ranged from 69.6% to 80.3%, all significantly exceeding the preset target threshold of 40%, and all higher than the 65.3% improvement of the synthetic dataset with a control size of 5000 packets. Among them, the BATADAL water SCADA dataset showed the highest performance improvement, reaching 80.3%, which perfectly matches the typical water SCADA communication characteristics of this dataset, which is primarily read-based. Figure 3 As shown, this dataset has approximately 85% read operations and very low write operations. The fast path designed for read operations in this invention can completely skip SM3 hash calculations; the higher the proportion of read operations, the more significant the optimization benefit. The average performance improvement on five publicly available PCAP datasets reaches 72.4%. See the test results for details. Figure 8 This fully demonstrates the broad applicability of this solution in real industrial control network traffic scenarios.

[0075] (4) Comparison of data packet size growth The test results for packet size and bandwidth overhead are shown in Figure 6. The lightweight scheme of this invention increased the packet size by 117.7% to 123.6% after encryption, with an average of approximately 120.5% across all test scales. The baseline scheme defined in Table 3 uses AES-256-CBC full-packet encryption combined with dense SM3 packet-by-packet updates, and its packet size increase ranges from 162.2% to 169.3%, with an average of approximately 165.4%. Figure 6As shown, the bandwidth overhead of the present invention is about 45 percentage points lower than that of the baseline solution. This has significant practical engineering value for industrial control network scenarios where bandwidth resources are generally limited. Typical scenarios include uplinks via RS-485 serial bus to TCP gateway.

[0076] (5) Cross-dataset pattern of SM3 hash reduction Table 4 shows the test results. In the five publicly available industrial control PCAP datasets, the reduction in SM3 hash calls remained stable between 94.0% and 97.0%, all higher than the 90.3% reduction in the synthetic dataset with 5000 packets as a control. This trend is entirely consistent with the performance improvement across datasets. The core reason is that the proportion of read operations in the publicly available industrial control PCAP datasets is generally higher than 50% in the synthetic dataset. Read operations generate a large amount of SM3 hash call overhead in the baseline solution, while the lightweight solution of this invention completely skips SM3 computation for read operations. Therefore, in real-world industrial control scenarios with a high proportion of reads, it can achieve a more significant saving effect in hash computation overhead.

[0077] Preferably, this embodiment describes the complete algorithm flow of the lightweight encryption method of the present invention using structured pseudocode, so as to facilitate implementation on various embedded platforms.

[0078] Algorithm 1 Lightweight Encryption Subprocess (Sender) Input: raw Modbus TCP packet, SM4 key, hash chain state H, pending_count counter, sequence number seq, step size N; Output: encrypted_packet, updated H, updated pending_count, updated seq; 1. seq ← seq + 1 2. fc ← packet.function_code 3. if len(packet.data) ≥ 2 then 4. addr ← packet.data[0:2] 5. rest ← packet.data[2:] 6. critical_bytes ← fc ∥ addr / / 3-byte critical_byte group 7. ← critical_bytes ∥ seq_bytes(2B) ∥ (0x0B × 11) / / Embedded seq to prevent replay, each time is different 8. C ← SM4_ECB_ENC(key, P) / / SM4-ECB encryption 9. if fc ∈ {0x05, 0x06, 0x0F, 0x10} then / / Write the operation path 10. pending_count ← pending_count + 1 11. if pending_count ≥ N then 12. H ← SM3(H ∥ critical_bytes)[0:8] / / Hash chain update 13. pending_count ← 0 14. end if 15. ICV ← H / / Current hash chain value 16. else / / Fast path for read operations 17. ICV ← 0x0000000000000000 / / 8-byte zero value 18. end if 19. length ← 16 + 8 + len(rest) + 1 20. encrypted_packet ← MBAP(tid, pid, length, uid) ∥ C ∥ ICV ∥rest 21. else / / Short message processing 22. P ← fc ∥ (0x0F × 15) 23. C ← SM4_ECB_ENC(key, P) 24. ICV ← 0x0000000000000000 25. encrypted_packet ← MBAP(tid, pid, 25, uid) ∥ C ∥ ICV 26. end if 27. return encrypted_packet, H, pending_count, seq.

[0079] The execution process of Algorithm 1 is as follows: Line 1 atomically increments the global sequence number seq to assign a unique identifier to this message. Its monotonically increasing nature forms the numerical basis for replay detection at the receiving end. Line 2 reads the PDU function code fc, which serves as the basis for subsequent operation type branch judgment. Line 3 checks whether the length of the PDU data field is not less than 2 bytes. If the condition is met, the normal format message enters the main processing branch; otherwise, it enters the short message fallback branch in lines 21 to 25.

[0080] In the main processing branch, lines 4 and 5 split the PDU data field into the starting address addr (2 bytes) and the remaining numerical payload rest; line 6 concatenates the function code and the starting address in sequence to form a 3-byte critical_bytes group, which is the minimum complete representation of the control instruction semantics; line 7 appends 13 bytes of padding (value 0x0D, i.e., the padding length itself, compatible with PKCS#7 specification) after the critical_bytes group to form a 16-byte SM4 plaintext block P; line 8 calls the pre-created SM4 encryption context to perform ECB mode single-block encryption to obtain a 16-byte ciphertext block C. Here, the SM4 context has completed key expansion during the initialization phase, and there is no repeated expansion overhead in the high-frequency call path.

[0081] Lines 9 to 18 perform operation type-based processing. When fc belongs to the write operation set {0x05, 0x06, 0x0F, 0x10}, line 10 increments pending_count; lines 11 to 14 perform sparse update judgment: if pending_count reaches the step size threshold N, hash chain iteration is performed and pending_count is reset to zero; otherwise, SM3 calculation is skipped; line 15 takes the current hash chain state value H as the ICV of this message. Regardless of whether an update is triggered, the ICV field is filled with the latest H value to ensure that the write operation sequence within the same step length carries a consistent integrity flag. When fc does not belong to the write operation set (read operation), line 17 directly assigns the ICV to an 8-byte all-zero vector, completely skipping pending_count update and SM3 calculation, completing the processing with minimal overhead.

[0082] Lines 19 and 20 recalculate the MBAP length field and assemble the encrypted message according to the specified offset structure: the 7-byte MBAP header, the 16-byte SM4 ciphertext block C, the 8-byte ICV, and the variable-length remaining payload rest are concatenated in this order to generate the final encrypted message byte string. Line 27 returns the encrypted message and four updated state variables to maintain the continuity of the chained state for the next call.

[0083] Algorithm 2 Lightweight Decryption Subprocess (Receiver) Input: encrypted_packet, SM4 key, expected_seq, local hash chain state H_local; Output: Raw data packet (or REJECT signal); 1. Parse the encrypted_packet to obtain seq_recv, unit_id, C (16B), ICV (8B), and rest. 2. if seq_recv ≠ expected_seq then 3. return REJECT / / Serial number is invalid, discard. 4. end if 5. P_dec ← SM4_ECB_DEC(key, C) 6. padding_len ← P_dec

[15] 7. if padding_len < 1 or padding_len > 16 then return REJECT end if 8. critical_bytes ← P_dec[0 : 16 - padding_len] / / Remove padding 9. fc ← critical_bytes[0] 10. addr ← critical_bytes[1:3] 11. if fc ∈ {0x05, 0x06, 0x0F, 0x10} then / / Update the hash chain first, then verify the ICV. 12. pending_count_local ← pending_count_local + 1 13. if pending_count_local ≥ N then 14. H_local ← SM3(H_local ∥ critical_bytes)[0:8] 15. pending_count_local ← 0 16. end if 17. If ICV ≠ H_local then / / Use the updated H_local for verification 18. return REJECT / / Modify or replay 19. end if 20.end if 21. packet ← ModbusTCPPacket(tid, pid, unit_id, fc, addr ∥ rest) 22. expected_seq ← expected_seq + 1 23. Return packet.

[0084] The execution process of Algorithm 2 is as follows: Line 1 parses the received message field by field according to the encrypted message offset structure defined in this invention, extracting the ciphertext block C (byte offset 7 to 22), ICV (byte offset 23 to 30), and the remaining payload rest (byte offset 31 to the end). Lines 2 to 4 perform sequence number continuity verification, comparing the received seq_recv with the local expected value expected_seq. If they do not match, REJECT is returned directly and the message is discarded. This is the first line of defense for security verification, which can effectively block replay messages (seq_recv is less than expected_seq) and out-of-order messages. This verification only requires one integer comparison, with extremely low overhead.

[0085] Line 5 performs ECB mode decryption using the pre-created SM4 decryption context, restoring the 16-byte plaintext block P_dec. Lines 6 and 7 read the last byte of the plaintext block as the padding length padding_len and verify its validity. If it exceeds the range, a REJECT is returned to prevent abnormal access in case of key mismatch or message corruption. Lines 8 and 10 remove the padding bytes and restore the function code fc and starting address addr from the first (16-padding_len) bytes of the plaintext block, completing the reverse operation of lines 6 and 7 of the sending end.

[0086] Line 11 merges the hash chain update and ICV verification into a single write operation branch, ensuring that H_local is updated first, followed by ICV comparison: First, pending_count_local is incremented using a step-size strategy. If the threshold N is reached, SM3 iterative updates H_local are performed, and the counter is cleared, synchronizing the hash chains of the receiver and sender before the comparison. Then, the ICV carried in the packet is compared with the updated H_local; if they do not match, REJECT is returned. Line 21 concatenates the restored key byte group with the remaining payload rest from transparent transmission, reconstructing the complete original Modbus TCP packet for delivery to the upper-layer application. Line 22 only increments expected_seq after the packet has passed all verifications, preventing attackers from disrupting the sequence number window by constructing a large number of illegal packets.

[0087] The lightweight encryption method of this invention can be deployed in existing industrial control systems in the following three ways to meet the transformation needs of different scenarios: (1) Firmware Integration Mode: The lightweight encryption module is integrated into the firmware of industrial control terminal devices such as PLCs and RTUs in the form of a static library or source code. The encryption and decryption interface is called at the application layer of the Modbus TCP communication protocol stack to achieve end-to-end transparent encryption. This mode does not require network topology changes and is suitable for new industrial control devices with firmware upgrade capabilities.

[0088] (2) Security Gateway Proxy Mode: A lightweight security gateway device is deployed at the boundary of the industrial control network. The gateway performs encryption processing of plaintext Modbus TCP packets according to the scheme of this invention and then forwards them to the external network; the receiving gateway decrypts the encrypted packets and then forwards them to the internal industrial control equipment. This mode does not require modification of the end devices and is suitable for batch security hardening scenarios of a large number of old and non-upgradeable devices.

[0089] (3) Software library integration mode: The present invention is implemented as a standard Python / C dynamic library for direct call by industrial control application software to achieve end-to-end encryption at the application layer without modifying the underlying Modbus TCP protocol stack or network hardware.

[0090] Based on the same inventive concept as the foregoing method embodiments, this embodiment of the invention also provides a lightweight data encryption acquisition system, including: Message parsing unit: Parses Modbus TCP messages, extracts the function code and start register address as key byte code (3 bytes), and separates the MBAP header and remaining data payload.

[0091] SM4 encryption unit: The pre-extended SM4 round key, after adding 13 bytes of padding to the 3-byte key byte, is encrypted into a 16-byte ciphertext block using ECB mode.

[0092] Logical Distribution Unit: Determines read / write operations based on the function code. For read operations, it instructs the ICV to be padded with 8 bytes of all zeros; for write operations, it maintains a counter `pending_count` for the sparse hash chain and the current hash state `current_hash` (initially generated by an SM3 random seed). A step size N determines whether to trigger a hash update: `pending_count` increments; if it reaches N, the SM3 verification unit is called to update the hash chain and clear the counter; otherwise, the current hash value is reused as the ICV. The receiving end synchronously maintains the hash state and verifies the ICV.

[0093] SM3 check unit: performs SM3 hashing, supports hash chain iteration (concatenates the current hash value with the key byte group, performs calculations, and outputs the first 8 bytes).

[0094] Message assembly unit: Concatenates the MBAP header (length field recalculated), SM4 ciphertext block (16 bytes), ICV (8 bytes), and remaining payload in sequence to generate an encrypted message.

[0095] Each unit works in concert to achieve hierarchical reading and writing processing and sparse hash chain verification.

[0096] This invention also provides a transmitting device, including a memory and a processor.

[0097] Memory: Stores the SM4 key, step size N, current hash chain state H (8 bytes), counter pending_count, and global sequence number seq.

[0098] The processor performs the following steps: Parses the original Modbus TCP packet, extracts the function code and start register address, and constructs a 3-byte key block. The sequence number is incremented and embedded in the packet (reusing the transaction ID or extended field). The key block is padded with 13 bytes, and SM4-ECB is used to encrypt it into a 16-byte ciphertext block. For read operations, ICV is set to 8 bytes of all zeros; for write operations, pending_count is incremented: if pending_count < N, ICV takes the current H; if pending_count ≥ N, H = SM3(H ∥ key block)[0:8] is calculated, H is updated, and the counter is cleared, and ICV takes the new H. The packet is reassembled: MBAP header (length recalculated) + ciphertext block + ICV + remaining payload, and the encrypted packet is sent.

[0099] This invention also provides a receiving device, including a memory and a processor.

[0100] Memory: Stores the SM4 key, step size N, local hash chain state H_local (8 bytes), local counter pending_local, and expected sequence number expected_seq.

[0101] The processor executes the following steps: It receives the encrypted message and extracts the sequence number, SM4 ciphertext block (16 bytes), ICV (8 bytes), and remaining payload. It verifies the sequence number: if it does not match expected_seq, it discards the message and issues an alarm. It decrypts the ciphertext block using SM4-ECB, removes padding, and restores the key byte group (function code + start address). For write operations: it compares ICV with H_local; if they do not match, it discards the message. After successful verification, it updates H_local and pending_local according to the same time-growth strategy as the sender (incrementing automatically, performing SM3 iteration and clearing to zero when N is reached). It concatenates the restored key byte group with the remaining payload to reconstruct the original Modbus TCP message, delivers it to the upper-layer application, and increments expected_seq by 1.

[0102] In summary, this invention discloses a lightweight encrypted transmission and acquisition method for Modbus TCP based on the national cryptographic standards SM4 and SM3, belonging to the field of information security for industrial control systems. Addressing the problems of high encryption latency and poor real-time performance caused by limited computing resources in industrial control nodes, this invention proposes a key byte encryption strategy. Specifically, it extracts only the function code and register address from the Modbus PDU as the key byte and encrypts them using the national cryptographic standard SM4 algorithm. Simultaneously, for integrity verification requirements, this invention designs a sparse hash chain mechanism based on the SM3 algorithm, verifying only write operations and updating the hash seed every N operations, while reusing the current hash for other operations. For high-frequency read operations, this invention employs a fast path with zero integrity overhead. Experimental data shows that this invention significantly reduces the hash calculation frequency while ensuring compliance with national cryptographic standards, improving system processing efficiency by over 65% on synthetic datasets and by 69.6% to 80.3% on five publicly available industrial control PCAP datasets. This invention is suitable for industrial control data acquisition and control scenarios with extremely high real-time requirements.

[0103] The above embodiments have described specific implementations of the present invention without departing from its core technical solution. Those skilled in the art should understand that the present invention can be provided as a method, system, or computer program product. Therefore, the present invention can take the form of a completely hardware embodiment, a completely software embodiment, or an embodiment combining software and hardware aspects. Furthermore, the present invention can be implemented as a computer program product embodied on one or more computer-usable storage media (including but not limited to disk storage, flash memory, CD-ROM, optical storage, etc.) containing computer-usable program code.

[0104] Finally, it should be noted that the above embodiments are only used to illustrate the technical solutions of the present invention, and not to limit them; although the present invention has been described in detail with reference to the foregoing embodiments, those skilled in the art should understand that modifications can still be made to the technical solutions described in the foregoing embodiments, or equivalent substitutions can be made to some or all of the technical features therein; and these modifications or substitutions do not cause the essence of the corresponding technical solutions to deviate from the technical solutions of the embodiments of the present invention.

Claims

1. A lightweight encryption method for Modbus TCP protocol based on Chinese national cryptographic standards SM4 and SM3, characterized in that, include: Parse the Modbus TCP raw message and extract the function code and register address from the Protocol Data Unit (PDU) as the key byte code; The keyword bytecode is encrypted using the national cryptographic SM4 algorithm to generate a fixed-length encrypted block and replace the corresponding field in the original message; The operation type of the current message is determined based on the function code, and a hierarchical processing path is executed: if it is a read operation, the fast path is used, and the encrypted message is sent directly to the data acquisition end without performing integrity verification; if it is a write operation, the sparse hash chain verification mechanism based on the national cryptographic SM3 algorithm is triggered. The sparse hash chain verification mechanism calculates the integrity verification value (ICV) based on a preset update step size N, and embeds the ICV at the end of the message along with the data transmission.

2. The method according to claim 1, characterized in that, The keyword bytecode is composed of a 1-byte function code and a 2-byte start register address.

3. The method according to claim 1, characterized in that, The encryption process of the key bytecode using the national cryptographic SM4 algorithm is as follows: the 3-byte key bytecode is supplemented with a 2-byte big-endian sequence number and 11 bytes of fixed padding value to make a total of 16 bytes, and then encrypted using a preset key in ECB mode of the SM4 algorithm.

4. The method according to claim 1, characterized in that, The write operation is defined in the range of function codes 0x05, 0x06, 0x0F and 0x10; the read operation is any operation other than the write operation defined in the range.

5. The method according to claim 1, characterized in that, The sparse hash chain verification mechanism specifically includes: The system maintains a global counter and a current hash state value; The global counter increments whenever a write operation message is captured; When the global counter is less than the update step size N, the current hash state value is directly assigned to the ICV of the current message; When the global counter is greater than or equal to the update step size N, the SM3 algorithm is used to perform a hash operation on the current hash state value and the key bytecode of the current message, update the current hash state value and clear the global counter.

6. The method according to claim 5, characterized in that, The update step size N is a configurable parameter; the ICV is 8 bytes, and for read operations, the ICV is filled with 8 bytes of all zeros.

7. The method according to claim 1, characterized in that, The method also includes a message reassembly process: retaining the original MBAP header, sequentially concatenating the 16-byte SM4 ciphertext, the 8-byte ICV checksum, and the remaining data payload in the original message, and synchronously modifying the length field in the MBAP header according to the total length after concatenation.

8. A lightweight data encryption acquisition system implementing the method of any one of claims 1-7, characterized in that, include: The message parsing unit is used to parse Modbus TCP raw messages and extract the function code and register address from the protocol data unit (PDU) as key byte codes. The SM4 encryption unit is used to encrypt the keyword bytecode using the national cryptographic SM4 algorithm to generate a fixed-length encryption block. The logical distribution unit is used to determine the operation type of the current message based on the function code, distinguish the read and write paths, and maintain the state of the sparse hash counter. The SM3 verification unit is used to trigger a sparse hash chain verification mechanism based on the national cryptographic SM3 algorithm when a write operation is detected, and calculates the integrity verification value ICV according to the preset update step size N.

9. A transmitting device, characterized in that, include: Memory, used to store computer programs; A processor, when executing the computer program, implements the steps of the sending end in the method of any one of claims 1 to 7, the steps including: parsing the Modbus TCP packet to be sent, extracting the keyword bytecode and performing SM4 encryption; Determine whether to trigger SM3 sparse hash chain calculation to generate ICV based on the operation type; embed the encrypted block and ICV into the original message, reassemble and send the encrypted message.

10. A receiving device, characterized in that, include: Memory, used to store computer programs; The processor, when executing the computer program, performs the following steps: receiving an encrypted message, extracting an SM4 ciphertext block and decrypting it to restore the keyword byte; Extract ICV and perform integrity verification on write operation messages based on the locally maintained hash chain state and update step size N; After successful verification, the original Modbus TCP packet is reassembled.