A national secret algorithm acceleration system based on Numba instant compilation technology

By reconstructing the core module of the Chinese cryptographic algorithm based on Numba just-in-time compilation technology, the performance bottleneck and maintainability issues of the Chinese cryptographic algorithm in dynamic environments are solved, achieving efficient and flexible acceleration of the Chinese cryptographic algorithm and supporting the engineering application of post-quantum cryptography algorithms.

CN120560665BActive Publication Date: 2025-11-18SOUTHWEST PETROLEUM UNIV
View PDF 1 Cites 0 Cited by

Patent Information

Application Number
CN202511057593.X
Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
Filing Date
2025-07-30
Publication Date
2025-11-18
Estimated Expiration
2045-07-30

AI Technical Summary

Technical Problem

Existing national cryptographic algorithms are difficult to adapt to dynamic changes in cloud computing and edge computing environments. Hardware acceleration solutions are highly closed, traditional optimizations lead to deterioration in maintainability, static compilation affects code auditability, and they cannot break through the efficiency limit of a single node. Post-quantum cryptographic algorithms are not adequately prepared, and their algorithm agility and cross-platform deployment capabilities are insufficient.

Method used

It adopts Numba just-in-time compilation technology, reconstructs the core computing module of the national cryptographic algorithm through the LLVM compilation chain, uses the @njit decorator to accelerate the compilation of key functions, dynamically identifies hot operations and loads differentiated instruction optimization strategies, builds a layered architecture, provides standardized API interfaces, and optimizes the SM2, SM3, SM4 and ZUC algorithms by combining key generation, secure storage and front-end interaction.

Benefits of technology

It achieves high-performance optimization of national cryptographic algorithms under general computing architecture, maintains code maintainability and cross-platform compatibility, significantly improves algorithm execution efficiency, reduces integration complexity, supports plug-and-play post-quantum cryptography algorithms, and accelerates the platform to have forward-looking expansion capabilities.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN120560665B_ABST
    Figure CN120560665B_ABST
Patent Text Reader

Abstract

The application relates to the field of national secret algorithm acceleration technology and discloses a national secret algorithm acceleration system based on Numba instant compiling technology, a core algorithm layer is used for reconstructing a numerical calculation mode of SM2 elliptic curve scalar multiplication, SM3 message expansion round function, SM4 nonlinear transformation and ZUC flow generation logic contained in a national secret algorithm core calculation module by using an LLVM compiling chain of Numba, converting Python code of interpretation execution into optimized machine code suitable for hardware adaptation, realizing key function compiling acceleration through an @njit decorator, dynamically identifying hot operation through compiling scheduling and loading a differentiated instruction optimization strategy, and the platform showing multiple technical advantages: in the aspect of development efficiency, the integration complexity of the national secret algorithm is greatly reduced through preset standardized acceleration module library and automatic compiling tool chain; in the aspect of running performance, the compiling optimization depth is superior to that of a general interpreter acceleration scheme; and in the aspect of safety controllability, the mathematical theoretical basis of the national secret algorithm is completely reserved, and hidden risks possibly introduced by black box type hardware acceleration are avoided.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of Chinese cryptographic algorithm acceleration technology, specifically to a Chinese cryptographic algorithm acceleration system based on Numba just-in-time compilation technology. Background Technology

[0002] Existing technological approaches are facing a multi-dimensional dilemma: hardware acceleration solutions are constrained by the closed ecosystem of dedicated chips, making them difficult to adapt to dynamic environments such as cloud computing and edge computing; traditional optimizations based on low-level languages ​​require deep involvement in the underlying implementation, leading to a deterioration in algorithm maintainability; static compilation technology sacrifices code auditability for limited performance gains, failing to pass security audits of cryptographic modules; while distributed architectures alleviate throughput pressure through horizontal scaling, they cannot overcome the physical limits of single-node execution efficiency. Meanwhile, post-quantum cryptographic algorithms are not adequately prepared for engineering, and the existing national cryptographic system suffers from generational gaps in algorithmic agility and cross-platform deployment capabilities, making it difficult to address the security challenges of the quantum computing era.

[0003] Against this backdrop, there is an urgent need to build a new generation of national cryptographic algorithm engineering technology system. Under the premise of ensuring the correctness and compliance of cryptography, we should break through performance bottlenecks, reduce integration complexity, strengthen key security management, and optimize human-computer interaction experience, so as to promote the development of domestic cryptographic technology from standard setting to industrial in-depth development and build a solid security foundation for the construction of Digital China. Summary of the Invention

[0004] To address the aforementioned shortcomings in existing technologies, this invention provides a national cryptographic algorithm acceleration system based on Numba just-in-time compilation technology. By deeply integrating cryptographic mathematical models with dynamic compilation optimization mechanisms, it constructs an algorithm acceleration system that balances performance and maintainability. Its core innovation lies in: utilizing Numba's LLVM compilation chain to reconstruct the numerical computation mode of the core computational modules of the national cryptographic algorithm (including SM2 elliptic curve scalar multiplication, SM3 message extension round function, SM4 nonlinear transformation, and ZUC stream generation logic), converting the interpreted Python code into hardware-adapted optimized machine code, thus overcoming performance bottlenecks while maintaining code readability. The platform adopts a layered architecture design. The algorithm kernel layer accelerates the compilation of key functions through the @njit decorator; the compilation scheduling layer dynamically identifies hot operations and loads differentiated instruction optimization strategies; and the service interface layer provides standardized APIs for seamless integration with existing cryptographic service systems. Compared to hardware acceleration solutions, this platform avoids dependencies on dedicated instruction sets, achieving performance balance across x86 / ARM architectures. Compared to static compilation techniques, it retains complete code auditability and supports rapid algorithm iteration and upgrades. Addressing the efficiency shortcomings of pure Python implementations, it utilizes just-in-time (JIT) compilation technology to improve the performance of critical operations by several times. Furthermore, the platform comes pre-installed with acceleration module libraries certified by the State Cryptography Administration, allowing developers to obtain acceleration capabilities through simple interface calls without needing in-depth knowledge of compiler principles. This significantly reduces integration complexity and provides a high-performance, highly flexible engineering foundation for building the national cryptographic algorithm ecosystem.

[0005] To achieve the above-mentioned objectives, the technical solution adopted by this invention is as follows:

[0006] A national cryptographic algorithm acceleration system based on Numba just-in-time compilation technology includes:

[0007] The core algorithm layer utilizes Numba's LLVM compilation chain to reconstruct the numerical computation mode of the core computation module of the national cryptographic algorithm, including SM2 elliptic curve scalar multiplication, SM3 message extension round function, SM4 nonlinear transformation, and ZUC stream generation logic. It converts the interpreted Python code into hardware-adaptive optimized machine code and accelerates the compilation of key functions through the @njit decorator. It also dynamically identifies hot operations and loads differentiated instruction optimization strategies through compilation scheduling.

[0008] The data model layer is used to map the underlying database table structure through the key model;

[0009] The business service layer is used to implement key generation, secure storage, distribution, rotation, auditing, and destruction through key services.

[0010] The API interface layer is used to build a RESTful API service layer based on the FastAPI framework, and to implement service encapsulation, key management interface and performance monitoring.

[0011] The front-end application layer is used to build front-end systems based on Vue 3 and Element Plus, and to realize user interaction through interface design, function implementation and technical architecture.

[0012] Furthermore, the core algorithm layer reconstructs the numerical computation mode for SM2 elliptic curve scalar multiplication, including:

[0013] The parameters are pre-calculated and stored using the pre_kG function. The query matrix, the It is a predefined fixed point on the selected elliptic curve, forming a two-dimensional lookup table of 32 rows × 255 columns, and stored as a binary file SM2_kG.bin;

[0014] The Montgomery modular multiplication algorithm is implemented using the C extension library _ec_lib. The operands are converted to the Montgomery field for calculation and finally converted back to the ordinary field.

[0015] Inverse pre-computation is performed during SM2 class initialization.

[0016] calculate And solve , It is a modulo operation.

[0017] Cache the results for the signature function. ; It is the final generated digital signature pair The second key component; For the signer's private key, the It is a confidential integer; It is a temporary random number; It is the first component in the signature pair. It's a temporary point. Coordinates; and n is the base point of the elliptic curve. The order;

[0018] Using the Jacobi coordinate system to represent affine coordinate points Mapped to three-dimensional Jacobian coordinates The ,

[0019] The ;

[0020] Implement dot addition and doubling operations in the ec_ws_add and ec_ws_double functions;

[0021] Use ctypes to load and define function prototypes, and load pre-computed data when the ECC_Curve class is initialized.

[0022] Furthermore, the core algorithm layer reconstructs the numerical calculation mode of the SM3 message extension round function, including:

[0023] Use `np.frombuffer` to create an array directly from a byte stream. Apply the `@njit` decorator to statically compile the compression function `CF` and the helper function `i8_u4`, converting the dynamically typed Python code into an LLVM (Low Level Virtual Machine) intermediate representation.

[0024] The Boolean function operations involved convert branch judgments into bitwise operation expressions; NumPy's uint32 type arrays ensure that state variables are stored contiguously in memory, providing support for branchless vectorized (SIMD) vectorized parallel computing for the JIT (Just-in-Time) compiler; and preloads round constants while directly compiling bitwise operations such as circular left shift into efficient native CPU instructions.

[0025] Furthermore, the core algorithm layer reconstructs the numerical computation mode of the SM4 nonlinear transform, including:

[0026] The 8-bit S-box is expanded into a 16-bit pre-computed lookup table by pre-compiling and storing the replacement results corresponding to all possible 16-bit input values;

[0027] We implement block-level parallel encryption in Electronic Codebook (ECB) mode using the @njit(parallel=True) decorator and prange parallel iterator; we perform multi-threaded parallel processing on independent data blocks during the encryption process and combine a cache-friendly block partitioning strategy to optimize the throughput of large batches of data.

[0028] By using compilation optimization techniques such as loop unrolling and register reuse, the core linear transformation function is compiled into a branchless vectorized (SIMD) instruction sequence;

[0029] In-place state update technology is used to reduce memory copy overhead, and round key buffers are securely pre-allocated through thread-local storage to support high-concurrency encryption and decryption;

[0030] The core computational logic within the round function is restructured, merging independent nonlinear byte replacements and linear diffusion transformations into a single composite algebraic operation, aiming to reduce function call overhead and the number of times intermediate results are accessed.

[0031] All system parameters and round constants required during the encryption process are pre-calculated and cached.

[0032] Furthermore, the core algorithm layer reconstructs the numerical computation mode of the ZUC flow generation logic, including:

[0033] The conditional shift operation in the core state update is reconstructed into a branchless arithmetic shift and mask combination, and the modulo reduction operation is merged through continuous bit operations to eliminate the branch prediction overhead.

[0034] The linear transformation and nonlinear S-box lookup in bit reconstruction are separated into independent pipeline stages, and a pure arithmetic logic unit (ALU) instruction sequence is generated through multi-level bit shift XOR logic. At the same time, the lookup operation is optimized into efficient register loading by using pre-computation and constant folding techniques.

[0035] By using the forced inlining optimization of the JIT compiler, the overhead of calling the core state update function is eliminated, and the state variables of the linear feedback shift register (LFSR) are directly mapped to register operations. At the same time, a data view is created using zero-copy technology to avoid memory copying.

[0036] By using loop unrolling and software pipeline techniques, the state update and key generation operations are executed in overlapping manner for four consecutive rounds.

[0037] The extended mode of ZUC-256 utilizes the Advanced Vector Extensions (AVX2) instruction set to process multiple 32-bit words simultaneously, achieving parallel processing based on SIMD instructions.

[0038] Furthermore, the core algorithm layer dynamically identifies hotspot operations and loads differentiated instructions through compilation scheduling optimization strategies, including:

[0039] By using a hotspot function identification mechanism, the runtime performance of the core modules of the algorithm is analyzed; by using sampling and call stack analysis to collect key performance indicators such as function call frequency and execution time, and by filtering the performance data based on preset thresholds, the most computationally intensive function modules are automatically identified and marked.

[0040] A dynamic loading mechanism based on compilation strategy is adopted. This mechanism first identifies the instruction set architecture supported by the processor through hardware feature detection; then, it selects the optimal set of compilation optimization parameters for the identified hot functions based on a decision model, and finally generates machine code adapted to the current hardware; then, it finely adjusts the instruction scheduling and memory access strategies according to the specific microarchitecture.

[0041] The system employs a caching management mechanism based on the compilation results. This mechanism maintains a persistent cache pool to store the compiled machine code and uses hash values ​​based on function signatures as unique identifiers for indexing. At the same time, the system uses an LRU cache replacement strategy to dynamically manage the cache pool to optimize storage efficiency.

[0042] Furthermore, the data model layer maps the underlying database table structure through the key model, including:

[0043] The system implements multi-level encrypted key storage based on the SQLAlchemy ORM layer, mapping the underlying database table structure by defining the KeyModel data model. During persistence, the system uses the national standard block cipher algorithm to encrypt the key data, and this encryption process is transparent to the upper-layer application. Furthermore, the key itself used for encryption is securely derived from the user's master key through a password-based key derivation function, and the atomicity of the entire storage process is guaranteed by the database's transaction mechanism.

[0044] Furthermore, the business service layer implements key generation, secure storage, distribution, rotation, and audit destruction through key services, including:

[0045] A hardware entropy source-based true random number generator (TRNG) is accelerated using JIT compilation technology to achieve rapid generation of high-entropy keys. This process involves sampling and randomizing the original physical noise and performing real-time entropy evaluation according to the NIST SP800-90B standard to ensure that the final output random number meets cryptographic security requirements.

[0046] Secure distribution and encapsulation of key materials are achieved through national cryptographic asymmetric encryption protocols, and key rotation is carried out regularly by combining an automated lifecycle management strategy based on time and usage frequency. A version control mechanism ensures a smooth transition of business operations.

[0047] By constructing an immutable audit log based on a cryptographic hash chain, the entire lifecycle of key operations is tracked and recorded, and strict security destruction procedures are followed during the key destruction phase, including using professional instructions to overwrite the storage area and forcibly clearing memory residues to prevent key information from being recovered.

[0048] Furthermore, the API interface layer is built on the FastAPI framework to construct a RESTful API service layer, implementing service encapsulation, key management interfaces, and performance monitoring, including:

[0049] Standardized endpoints are adopted, and each endpoint strictly validates input parameters through a request model. At the same time, a dependency injection system is used to implement interface authentication, and encrypted requests are processed through an asynchronous processor. The underlying algorithm implementation is decoupled from the HTTP interface to achieve a service architecture with high cohesion and low coupling.

[0050] It adopts a key lifecycle management API to implement permission management through fine-grained role-based access control, defines key operation permission enumeration, and implements interface-level permission control in conjunction with middleware; at the same time, it ensures the atomicity of key operations through database transactions and supports the secure generation, storage, rotation and revocation of keys.

[0051] It features built-in performance monitoring capabilities and provides monitoring support to the front-end application layer, business service layer, and core algorithm layer. It also includes a built-in Prometheus metrics exposer, which injects monitoring code through middleware, defines key performance metrics, collects runtime data in real time, and exposes monitoring metrics through dedicated endpoints. Additionally, it has a custom logging middleware that records request details.

[0052] Furthermore, the front-end application layer is built on Vue 3 and Element Plus to construct the front-end system, implementing user interaction through interface design, function implementation, and technical architecture, including:

[0053] It adopts Vue 3 as the core framework, combined with the Composition API to achieve logic reuse and component-based development; it uses the Vite build tool to achieve fast hot reloading and efficient packaging; it introduces Pinia state management to replace Vuex to achieve cross-component data sharing and optimize the state management mechanism; and it uses Vue Router to implement routing control based on historical APIs.

[0054] On the key management page, the key display and pagination functions are implemented through table components and pagination controls, and the key operation interface is implemented in combination with dialog components; on the algorithm operation page, independent card layouts are designed for SM2, SM3, SM4 and ZUC respectively. Each card contains an input area, an operation area and a result display area, and integrates data loading animation and operation feedback prompts.

[0055] Theme switching and dark mode support are achieved through a CSS variable system, and responsive adaptation is ensured by combining Flex layout and Grid layout. At the same time, transition animations and keyframe animations are introduced to optimize page switching and component interaction, and multi-language support is achieved through an internationalization plugin. Role-based access control is implemented based on the RBAC model, and sidebar menus are dynamically generated and unauthorized access is blocked.

[0056] This invention offers the following advantages: The platform for Chinese cryptographic algorithms based on the Numba library, constructed in this invention, achieves high-performance optimization of these algorithms under general computing architectures through deep integration of just-in-time (JIT) compilation technology and cryptographic primitive design. Unlike traditional hardware-dependent acceleration solutions, this platform innovatively applies Numba's LLVM compilation chain to the core modules of the SM2 / SM3 / SM4 / ZUC algorithms. For computationally intensive operations such as elliptic curve multiplication, hash iteration round functions, and block encryption transformations, it significantly improves algorithm execution efficiency through numerical computation model reconstruction and instruction-level optimization, while maintaining code maintainability and cross-platform compatibility. The platform proposes a dynamic hotspot function compilation mechanism that automatically identifies key computational paths during algorithm execution and adaptively loads the optimal compilation strategy based on hardware characteristics, effectively balancing performance across different architectures (x86 / ARM). Compared to the traditional Python interpreted execution mode, this solution overcomes the performance bottleneck of interpreted languages ​​in cryptographic computation by avoiding the introduction of complex C / C++ extensions, providing a lightweight transformation path for algorithm iteration and upgrades. Compared with mainstream acceleration solutions, this platform exhibits multiple technical advantages: In terms of development efficiency, it significantly reduces the integration complexity of Chinese cryptographic algorithms through pre-built standardized acceleration module libraries and automated compilation toolchains; in terms of runtime performance, its compilation optimization depth surpasses that of general-purpose interpreter acceleration solutions; and in terms of security and controllability, it fully preserves the mathematical theoretical foundation of Chinese cryptographic algorithms, avoiding the hidden risks that black-box hardware acceleration may introduce. The platform architecture design possesses forward-looking scalability, supporting plug-and-play acceleration of post-quantum cryptography algorithms through modular compilation interfaces. Experimental verification shows that this technical approach can be effectively migrated to new algorithm systems such as lattice cryptography and multivariate cryptography, providing sustainable engineering support for the evolution of cryptographic technology and promoting the in-depth development of the Chinese cryptographic algorithm ecosystem towards high performance and high maintainability. Attached Figure Description

[0057] Figure 1 This is a diagram of the overall framework of the national cryptographic algorithm platform.

[0058] Figure 2 This is a diagram of the API interface documentation.

[0059] Figure 3 This is a diagram of the database model relationships.

[0060] Figure 4 This is a comparison chart of the performance of SM2 dot product.

[0061] Figure 5 This is a comparison chart of SM2 encryption / decryption performance.

[0062] Figure 6 This is a performance comparison chart for SM2 signature / verification.

[0063] Figure 7This is a performance comparison chart of SM3Hash (first hash).

[0064] Figure 8 This is a performance comparison chart of SM3Hash (continuous hashing).

[0065] Figure 9 This is a performance comparison chart for long messages in SM4.

[0066] Figure 10 This is a performance comparison chart for SM4 SMS messages.

[0067] Figure 11 This is a performance comparison chart of ZUC stream ciphers. Detailed Implementation

[0068] The specific embodiments of the present invention are described below to enable those skilled in the art to understand the present invention. However, it should be understood that the present invention is not limited to the scope of the specific embodiments. For those skilled in the art, various changes are obvious as long as they are within the spirit and scope of the present invention as defined and determined by the appended claims. All inventions utilizing the concept of the present invention are protected.

[0069] The national cryptographic algorithm integrated platform constructed in this invention achieves three core breakthroughs:

[0070] First, instruction-level optimizations were performed on the core code of the SM2 / SM3 / SM4 / ZUC algorithms based on Numba JIT just-in-time compilation technology;

[0071] Secondly, a full-process key lifecycle management system was designed to achieve trusted control over the entire chain of key generation, storage, distribution, rotation, and destruction.

[0072] Finally, a minimalist design philosophy was adopted to develop the user interface, integrating a visual strategy configuration engine and automated deployment tools. Combined with a unified RESTful API interface service, the algorithm integration cycle was compressed from weeks to hours. Through three-dimensional innovation—performance acceleration, management enhancement, and experience upgrade—this platform constructs a technical system covering the entire cryptographic service chain.

[0073] This invention proposes a national cryptographic algorithm acceleration platform based on Numba just-in-time compilation technology, which deeply optimizes the core computation modules of SM2 / SM3 / SM4 / ZUC algorithms. By reconstructing computationally intensive functions in the algorithms into Numba-compatible numerical computation modes, and utilizing its LLVM compiler to generate highly optimized machine code, the performance bottleneck of Python's native interpreted execution is overcome. The platform establishes an algorithm hotspot function registration mechanism, automatically identifies key computational paths such as signature verification, hash iteration, and block encryption, and dynamically loads the Numba JIT compilation acceleration module, achieving a significant improvement in algorithm execution efficiency. In the key management stage, the system implements a multi-level key storage architecture through ORM technology, and builds a secure distribution channel in conjunction with national cryptographic protocols, forming a full lifecycle management system covering generation, storage, and rotation. The front end is built on a component-based framework to construct a visual console, providing algorithm speedup monitoring and key policy configuration functions. The back end encapsulates accelerated national cryptographic services through standardized RESTful interfaces, supporting elastic deployment and high-concurrency calls in a cloud-native environment, constructing a full-link acceleration system from underlying algorithm optimization to upper-layer service integration. This platform offers the following advantages: 1) Unlike traditional Python interpreted execution, it utilizes Numba just-in-time (JIT) compilation technology to convert the core algorithms of SM2 / SM3 / SM4 / ZUC into LLVM-optimized machine code, breaking through performance bottlenecks while maintaining code maintainability. Compared to native Python implementations, signature verification speed is increased by 5-8 times, and it eliminates the need for C / C++ extension development, significantly reducing algorithm optimization complexity. 2) The overall framework is built upon national cryptographic algorithm standards with a rigorous mathematical foundation (such as SM2 elliptic curve parameter constraints), while the core acceleration modules employ Numba dynamic compilation technology, forming a dual advantage of "mathematical verifiability + high engineering performance." Compared to traditional pure hardware acceleration solutions, this platform achieves a balance between cross-platform deployment flexibility and computational efficiency while ensuring cryptographic correctness. 3) It includes a built-in pre-optimized Numba JIT algorithm module library, which has passed the testing and certification of the State Cryptography Administration. Compared to self-developed compiler solutions, developers do not need to reimplement the underlying algorithm logic; they only need to call standardized interfaces to obtain acceleration capabilities, shortening the integration cycle by more than 70%. The platform also provides an algorithm hotspot analysis tool, which supports fine-tuning and optimization for specific business scenarios.

[0074] like Figure 1 As shown, an embodiment of the present invention provides a national cryptographic algorithm acceleration system based on Numba just-in-time compilation technology, comprising:

[0075] The core algorithm layer utilizes Numba's LLVM compilation chain to reconstruct the numerical computation mode of the core computation module of the national cryptographic algorithm, including SM2 elliptic curve scalar multiplication, SM3 message extension round function, SM4 nonlinear transformation, and ZUC stream generation logic. It converts the interpreted Python code into hardware-adaptive optimized machine code and accelerates the compilation of key functions through the @njit decorator. It also dynamically identifies hot operations and loads differentiated instruction optimization strategies through compilation scheduling.

[0076] The data model layer is used to map the underlying database table structure through the key model;

[0077] The business service layer is used to implement key generation, secure storage, distribution, rotation, auditing, and destruction through key services.

[0078] The API interface layer is used to build a RESTful API service layer based on the FastAPI framework, and to implement service encapsulation, key management interface and performance monitoring.

[0079] The front-end application layer is used to build front-end systems based on Vue 3 and Element Plus, and to realize user interaction through interface design, function implementation and technical architecture.

[0080] This embodiment constructs a core acceleration engine for national cryptographic algorithms through a core algorithm layer.

[0081] The optimization of SM2 elliptic curve scalar multiplication focuses on reducing the real-time computational overhead of elliptic curve scalar multiplication and improving the efficiency of signature and verification.

[0082] 1. Base Point Pre-calculation and Fast Table Lookup: A 32-row × 255-column two-dimensional lookup table is pre-calculated and constructed using `pre_kG`, and saved as a binary file `SM2_kG.bin`. The row index `i` (from 0 to 31) corresponds to the byte position of the 256-bit scalar `k`, the column index `j` (from 1 to 255) corresponds to all possible non-zero values ​​of a byte, and each table entry `Table[i][j]` stores the pre-calculated point. .

[0083] During the execution of the ECC_Curve.kG_fast method, the input 256-bit scalar It is treated as a 32-byte array, and the system iterates through this array, processing each byte... Find the pre-calculated point in its corresponding row i Finally, the 32 points obtained are accumulated using elliptic curve point addition to obtain the final result R. Using this method, a complete 256-bit scalar multiplication operation, which originally required hundreds of point additions and multiplications in O(n) complexity, is optimized to only 31 point additions and 32 table lookup operations, thus greatly improving computational efficiency.

[0084] 2. Modular Multiplication and Reduction Operation Optimization: The Montgomery modular multiplication algorithm is implemented using the C extension library _ec_lib. Operands are converted to the Montgomery field for computation, and finally converted back to the normal field. This is specifically designed for SM2 prime numbers. A special form of this implements a fast reduction algorithm, which... Convert to Its core is to utilize prime numbers in the SM2 national cryptographic standard. A special structure is used to avoid the high-overhead division operation. This represents a large integer to be modulo-reduced. In this expression... and These represent the lower 256 bits and the higher 256 bits of the operand T to be reduced, respectively. This avoids the expensive division operation.

[0085] 3. Inverse pre-computation during the signature process: Inverse pre-computation is performed during the initialization of the SM2 class.

[0086] calculate And solve , It is a modulo operation to ensure that the final value also falls within the range of 0 to n-1;

[0087] Cache the results for the signature function. ,in It is the final generated digital signature pair The second key component in this expression. The private key representing the signer, It is a confidential integer; This is a temporary random number generated during each signing process that must be kept confidential; It is the first component in a signature pair, typically consisting of a message digest and a temporary random number. related; It's a temporary point. of Coordinates; and n is the base point of the elliptic curve. The order of is a public system parameter, and all operations are performed under the integer ring modulo n.

[0088] 4. Modular Inverse Optimization in Point Operations: The Jacobi coordinate system avoids performing modular inverse operations on every point operation. In this mode, affine coordinate points... Projected as three-dimensional Jacobian coordinates The two satisfy the conversion relationship. and .

[0089] The point addition and doubling operations are implemented in the ec_ws_add and ec_ws_double functions, and the modular inverse is performed only once when affine coordinates are finally required.

[0090] 5. Core Computation Library Integration: Core computations are implemented through the compiled ecc.pyd library. ctypes are used to load and define function prototypes, and pre-computed data is loaded during the initialization of the ECC_Curve class.

[0091] To accelerate SM3 hash iteration, the optimization focuses on improving the computational performance of hash iteration, mainly through NumbaJIT compilation technology and memory access optimization.

[0092] 1. Numba JIT Compilation and Static Compilation: The `@njit` decorator is applied to statically compile the compressed function `CF` and the helper function `i8_u4`. This converts Python's dynamically typed code into an LLVM intermediate representation, and after multiple levels of optimization including type inference, inline expansion, loop optimization, and vectorization, generates efficient machine code. This eliminates interpreter overhead and the Global Interpreter Lock (GIL) limitation, making function execution speed approach that of C.

[0093] 2. Pre-computed constant table and initial vector hard-coding: Pre-computed constants , rotate left in a circular operation It is fixed as a lookup table access, and the initialization vector is hard-coded. Reduce redundant calculations during runtime.

[0094] 3. NumPy array and memory alignment optimization: Utilize NumPy's uint32 type arrays to store intermediate states contiguously, including message expansion arrays. and Ensure memory alignment and cache prefetching efficiency to reduce L1 cache miss rate to below 5%.

[0095] 4. Simplified Branching and Register Operations via Bitwise Operations: The bitwise operation `j & 0x30` replaces the condition `j ≥ 16`, mapping intermediate variables to register operations. This expression leverages the bit distribution characteristics of the round number `j`—the result is zero when `j` is in the range [0, 15], and non-zero when `j` is in the range [16, 63]—thus transforming the high-overhead conditional branching into branchless, single-cycle arithmetic logic. This microarchitectural optimization, combined with mapping intermediate variables to register operations, significantly improves the execution efficiency of the instruction pipeline. Performance profiling verifies that it can optimize the CPU pipeline prediction failure rate to 1.2% and reduce the proportion of memory read / write instructions to 12%.

[0096] 5. Zero-copy data conversion: Use `np.frombuffer(data, dtype=np.uint8).astype(np.uint32)` to create an array directly from the byte stream. This avoids additional memory allocation and data copying.

[0097] 6. Boolean function condition optimization: Optimizing Boolean functions within the compression function. and Conditional optimizations are performed. In the standard algorithm, the specific logic of these two functions depends on the round number j, which introduces conditional branches in a direct implementation. Converting branch decisions into bitwise expressions reduces the performance penalty for failed branch predictions. Although the current implementation does not explicitly enable prange multithreaded parallelism and the @guvectorize vectorization directive, it still reduces the performance penalty for failed branch predictions.

[0098] For SM4 nonlinear transform reconstruction, optimization is mainly achieved through optimization of the nonlinear transform reconstruction, parallel encryption, and round key generation stages.

[0099] 1. S-box precomputation and memory access optimization: The 8-bit S-box defined in the standard is expanded to a 16-bit precomputation lookup table (SM4_S_BOX_FAST).

[0100] pass The replacement results for all possible 16-bit input values ​​are pre-computed and stored. Here, S_box refers to the standard core 8-bit nonlinear permutation function (S-box) in the SM4 algorithm, which maps an 8-bit input byte to a unique 8-bit output byte. This expression forms the mathematical basis for constructing the 16-bit pre-computed lookup table. 'a' and 'b' represent two independent 8-bit input operands, and the || symbol is the concatenation operator, representing the concatenation of two bit strings. This achieves a single memory access replacing two byte lookup operations, and optimizes the replacement of a 32-bit word that originally required four memory accesses to only two accesses, significantly reducing memory access latency and cache miss rate.

[0101] 2. Block-level parallel encryption: Block-level parallel encryption in ECB mode is implemented using the `@njit(parallel=True)` decorator and the `prange` parallel iterator. The input data is divided into 128-bit (16-byte) blocks.

[0102] pass This method enables multi-threaded parallel processing. Secondly, to collaboratively optimize memory access performance, it incorporates cache partitioning technology. The core of this technology lies in utilizing the CPU's internal cache hierarchy: L1 cache (Level 1 cache), the smallest but fastest memory, serving as the first stop for CPU data access; and L2 cache (Level 2 cache), which has a larger capacity and is slightly slower but still far faster than main memory. Combined with circular partitioning, large datasets are divided into sub-blocks suitable for L1 / L2 cache sizes, ensuring cache line alignment and locality optimization, thereby improving the instruction throughput of multi-core CPUs.

[0103] 3. Round Key Generation Stage Optimization: The linear transformation (L function) is compiled into a branchless SIMD instruction sequence through loop unrolling and register reuse. This function is a core linear diffusion layer, cryptographically designed to diffuse small changes in the input data throughout the entire 32-bit output word through a series of bitwise XOR and circular left shift operations, thereby enhancing the algorithm's resistance to attacks such as differential analysis. Parallel bitwise operations are implemented using the vpxor, vpsll, and vpsrl instructions from the AVX2 instruction set, eliminating conditional jump overhead and branch prediction failure penalties.

[0104] 4. In-place state update and zero-copy memory view: Employs in-place state update technology, through... Instead of creating a new array, directly modify the contents of the original array.

[0105] Combining zero-copy memory view `np.frombuffer(data, dtype=np.uint32).view(np.uint32)` avoids the overhead of data copying and type conversion. Pre-allocated round key buffers are stored locally in threads, reducing multi-threaded contention and synchronization overhead.

[0106] 5. Round Function Algorithm Reconstruction: Reconstructing the round function... The synthetic permutation T in the algorithm is used for reconstruction, where to These are four 32-bit status words that make up a 128-bit data block. rk is the 32-bit subkey used in this round, and ⊕ represents a bitwise XOR operation. T is the core synthetic permutation function in the round function; it is a single operation resulting from the merging and reconstruction of the nonlinear transformation τ and the linear transformation L'.

[0107] nonlinear transformation

[0108] With linear transformation This is combined into a single operation, reducing intermediate result storage and loading, and lowering register pressure and memory access frequency. This includes nonlinear transformations. Decompose a 32-bit input word A into four 8-bit bytes ( to The linear transformation L' function performs a non-linear replacement on each byte in parallel using a standard 8-bit S-box. The linear transformation L' function works by cyclically left-shifting the input word B by different bit positions. The later versions perform XOR operations to achieve linear data diffusion.

[0109] 6. Pre-calculation of system parameters and wheel constants: Pre-calculate system parameters. Route constant This avoids redundant calculations during the encryption process.

[0110] For deterministic compilation of the ZUC stream generator, optimization is mainly achieved through hardware instruction mapping and compile-time static optimization strategies.

[0111] 1. LFSR state machine update optimization: The 31-bit conditional shift operation is reconstructed into a branchless arithmetic shift-mask combination expression.

[0112] The failure of conditional jump prediction has been eliminated.

[0113] Through continuous bit operations Merging modulo reduction operations This enables the LLVM compiler to generate efficient rotl / rotr rotation instructions.

[0114] Where x and y are 31-bit status words; & 0x7FFFFFFF is a bitmask used to extract the lower 31 bits of the 32-bit addition result, while ≫ 31 is an arithmetic right shift operation used to capture any overflow bits that may occur; adding the two together yields an equivalent modulo reduction result.

[0115] 2. Nonlinear Filtering Stage Optimization: The linear transformation of bit recombination (BR) and S-box lookup are separated into independent pipeline stages. The former generates a pure ALU instruction sequence (such as the vpternlog instruction of AVX512) through a multi-stage shift-XOR chain. The latter utilizes a pre-computed two-byte S-box. and To achieve constant folding, the lookup table operation will be reduced. The code is compiled as a direct register load (mov instruction), where S0(X) represents a non-linear substitution performed on the 16-bit input word X. ≫8 and &0xFF are bitwise operations used to extract the high and low octets of X, respectively. The results are used as indices for a pre-computed two-dimensional lookup table _ZUC_S0, thus decomposing the 16-bit lookup operation into two efficient and cache-friendly 8-bit index memory accesses. Memory alignment triggers the CPU cache prefetch mechanism, increasing the L1 cache hit rate to near saturation (>99%).

[0116] 3. Function Inlining and Register Operations: The `lfsr_next` function is forcibly inlined using the `@njit` decorator in Numba. This eliminates function call stack overhead and maps LFSR state variables to register operations. Combined with zero-copy data conversion `np.frombuffer(data, dtype=np.uint8).view(np.uint32)`, memory access is minimized.

[0117] 4. Keystream generation function optimization: By using loop unrolling and software pipelining techniques, the state updates and key generation operations of four consecutive rounds are overlapped. This fully utilizes the superscalar execution capabilities of modern CPUs to improve instruction-level parallelism.

[0118] 5. SIMD Instruction Parallel Processing: For the extended mode of ZUC-256, parallel processing based on SIMD instructions is implemented. Multiple 32-bit words are processed simultaneously using the AVX2 instruction set, further improving throughput.

[0119] This embodiment designs a dynamic compilation scheduling system as a key component of the core algorithm layer (Numba JIT acceleration) of the national cryptographic algorithm platform. Through collaboration with the overall platform architecture, it achieves dynamic performance optimization of the national cryptographic algorithms. The system first uses a hotspot function identification mechanism to perform runtime performance analysis on the execution process of algorithms such as SM2, SM3, SM4, and ZUC at the core algorithm layer. It uses sampling counters and call stack backtracking techniques to collect performance indicators such as function call frequency, execution time, and memory access patterns, and stores the data in a performance event buffer.

[0120] This is then expressed as a threshold filtering algorithm.

[0121] in and These represent the execution time and the number of times function f is called, respectively. This expression determines the overall program execution time by comparing these two metrics. Compared with total number of calls Does the proportion of [something] simultaneously exceed the preset performance threshold? and This is used to determine whether function f is a computationally intensive hotspot. Frequently called computationally intensive functions, such as the SM2 dot product operation (kG_fast) and the SM3 compression function (CF), are automatically identified and marked as optimization candidates.

[0122] Next, the compilation strategy loading mechanism constructs a feature vector based on the characteristics of the target hardware architecture by querying the CPU's supported instruction set extensions using the cpuid instruction or / proc / cpuinfo.

[0123]

[0124] Each item in the vector (such as...) ) is a Boolean flag used to indicate whether the CPU supports a specific SIMD instruction set extension; and based on the decision tree model D:F→S, the optimal set of compilation parameters S is selected to generate highly optimized machine code for each algorithm module in the core algorithm layer, while adjusting the loop unrolling factor, instruction scheduling strategy and memory alignment parameters according to the characteristics of the processor microarchitecture.

[0125] Finally, the cache management mechanism maintains a persistent cache pool of JIT compilation results.

[0126] Hash by function signature

[0127] As the index key, {code}(f) represents the source code or bytecode of function f. This represents the set of parameters used during compilation; || represents a cascading operation, achieved by hashing the combination of the two parameters using SHA-256. The compiled machine code is stored in a shared memory region or a disk file (.jitcache), supporting cross-process sharing of compiled machine code and implementing a "compile once, execute many times" optimization strategy. The LRU algorithm periodically cleans up infrequently used compilation results. The coordinated operation of these three mechanisms enables the core algorithm layer's national cryptographic algorithm to adaptively select the optimal execution path based on the characteristics of the actual operating platform, significantly improving computational efficiency while maintaining algorithm security. This provides robust underlying performance support for the API interface layer to receive high-concurrency cryptographic service requests without altering its standardized interface or the calling logic of the business service layer.

[0128] This embodiment implements full lifecycle management of keys through a data model layer and a business service layer. This management system achieves full-process security control of keys through four key stages: key generation, secure storage, distribution and rotation, and auditing and destruction.

[0129] 1. Key Generation: Implemented in the "Key Service" of the business service layer. It utilizes a Numba-accelerated quantum random number generator (QRNG) in the core algorithm layer to achieve rapid generation of high-entropy keys. This generator employs a quantum noise sampling algorithm optimized with the @njit(fastmath=True) decorator. Generate high-quality random numbers, among which Represents the 256-bit random state of the previous iteration. The expression uses raw random samples collected in real time from a hardware entropy source, where α is an irrational constant (golden ratio) used to enhance the mixing effect, and ⊕ and · represent bitwise XOR and multiplication, respectively. This expression generates new random states by mixing historical states with new physical entropy source data and constraining it within a 256-bit modulo space. Meanwhile, the entropy estimator defined by NIST SP 800-90B... Real-time monitoring of randomness ensures that the entropy value is not lower than 0.997 bits / bit; this calculation is performed on all possible output symbols. probability of occurrence Instead of using a weighted summation (Σ) of base-2 logarithms, the original entropy is adjusted using the SM3 hash function to eliminate potential statistical biases. Finally, zero-copy memory management directly maps the generated random bytes to key material, ensuring the efficiency and security of key generation.

[0130] 2. Secure Storage: Primarily implemented in the "Key Model (key_models.py)" of the data model layer and managed by the "Key Service" of the business service layer. Multi-level encrypted key storage is implemented based on the SQLAlchemy ORM layer, mapping the underlying database table structure through the defined KeyModel data model (`id`, `key_name`, `key_type`, `key_value`, `iv`, `created_at`, `expires_at`, `status`). The database model relationship between users (User) and keys (Key) is as follows: Figure 3 As shown. The national cryptographic standard SM4-CBC mode is used. Achieve transparent encryption; among which This represents the i-th ciphertext block generated in the current computation. Here... This is the core SM4 symmetric encryption function, which uses a key K to encrypt the input data. The input part of the expression... This is the i-th plaintext data block to be encrypted, where ⊕ is the bitwise XOR operator, and... It is the previously generated ciphertext block. This is a random initialization vector. The key value is first processed by the PBKDF2 key derivation function before being stored in the database. The processed master key is encrypted, and atomicity is ensured through database transactions (Session.commit()), guaranteeing the security of the key during storage.

[0131] 3. Distribution and Rotation: Coordinated by the "Key Service" in the business service layer, and utilizing the SM2 encryption module in the core algorithm layer. Secure key transmission is achieved through a pre-compiled SM2 encryption module, using the recipient's public key $P_B$ to encrypt the session key $k$, generating ciphertext. ,in , , , The first part, C, represents the final output ciphertext formed by concatenating three parts (||). It is an elliptic curve point, obtained by performing a scalar multiplication operation between a temporary random number k and the public base point G of the curve. The purpose of this is to enable the recipient to compute the shared secret. Part Two It is the encrypted core data, which is generated by bitwise XOR (⊕) operation between the original plaintext M and a key stream generated by the key derivation function KDF. The input used by KDF here is thus derived. The sender uses a temporary random number k and the receiver's public key. Perform another scalar multiplication The coordinates of the obtained shared secret point. Part Three It is a message authentication code, which is generated by performing an SM3 hash operation on the coordinates of the shared secret point and the original plaintext M. This key is generated for the recipient to verify data integrity after decryption. It is used in conjunction with an automated rotation strategy (trigger:time:0 0 1 * *, usage_count:1000, action:generate_newkey, transition:active_archive, new→active) to periodically update the key, and a smooth transition is achieved through a key version control mechanism (incrementing the key_version field) to prevent security risks caused by long-term key use. These functions are provided externally through the key management route ( / api / keys) in the API interface layer.

[0132] 4. Auditing and Destruction: This is primarily managed and executed by the "Key Service" in the business service layer, and recorded through the data model layer. An integrated blockchain log system records the key operation trajectory, documenting key operation events.

[0133] via SM3 hash chain The system stores logs to ensure immutability and implements distributed consensus verification to ensure traceability of key usage. Within the key lifecycle audit and traceability system, the expression E = {timestamp, operation, key_id, operator, result} defines a structured KeyOperation Event record. Here, E is a data set, serving as the atomic unit for writing to the hash chain. Its internal parameters are defined as follows: timestamp is a high-precision timestamp used to accurately record the time the operation occurred; operation is an enumerated field describing the operation type, such as key generation, distribution, or destruction; key_id is a unique identifier for the key affected by the operation, used to associate it with a specific key entity; operator records the identity of the user or system process executing the operation to ensure accountability; and result indicates the final result status of the operation, such as success or failure. By encapsulating these key attributes in a single event record E, the system creates a complete and independent audit snapshot for each key operation. During the key destruction phase, a secure erase instruction set (write0xFF, write0x00, writerandom()×3) physically destroys the key. Sensitive data is locked by directly accessing memory pages (mlock / munlock) to prevent it from being swapped to disk. An explicit memory zeroing function (memset_s) is called immediately after the operation is complete to eliminate the risk of key leakage. These auditing and destruction operations will also provide corresponding management interfaces through the API interface layer.

[0134] In this embodiment, the API interface layer (FastAPI) is located between the front-end application layer and the business service layer, serving as the core portal for the platform to provide services to the outside world. The high-performance RESTful API service layer built on the FastAPI framework implements a complete service system through three core modules: algorithm service encapsulation, key management interface, and performance monitoring. Specific interface definitions can be found in [reference needed]. Figure 2 The API interface documentation shown is a schematic diagram.

[0135] 1. Algorithm service encapsulation: This module directly corresponds to Figure 1The API interface layer includes "SM2 Routing," "SM3 Routing," "SM4 Routing," and "ZUC Routing." Standardized endpoints conforming to the GM / T 0009 specification, such as / api / sm2 / sign, / api / sm3 / hash, and / api / sm4 / encrypt, are designed. Each endpoint rigorously validates input parameters through a request model to ensure data format conforms to national cryptographic standards. Simultaneously, a dependency injection system is used for interface authentication, and encrypted requests are handled by asynchronous processors. This decouples the underlying algorithm implementation (i.e., the SM2, SM3, SM4, and ZUC modules in the core algorithm layer) from the HTTP interface, achieving a highly cohesive and loosely coupled service architecture.

[0136] 2. Key Management Interface: This module corresponds to... Figure 1 The API interface layer includes a "Key Management" route ( / api / keys). A complete key lifecycle management API is designed, such as / api / keys / generate, / api / keys / rotate, and / api / keys / revoke. Fine-grained role-based access control (RBAC) is used for permission management, defining key operation permission enumerations and integrating middleware to implement interface-level permission control. Simultaneously, database transactions ensure the atomicity of key operations, supporting secure key generation, storage, rotation, and revocation. These interfaces work closely with the "Key Service (key_service.py)" in the business service layer and the "Key Model (key_models.py)" in the data model layer, providing full lifecycle management functionality for keys.

[0137] 3. Performance monitoring: Although this module... Figure 1 While not listed as a separate module, its functionality is embedded in the API interface layer, providing monitoring support both upwards (front-end application layer) and downwards (business service layer, core algorithm layer). It includes a built-in Prometheus metrics exposer, injecting monitoring code through middleware to define key performance indicators such as algorithm latency, data throughput, and cache hit rate. It collects runtime data in real time and exposes these metrics through dedicated endpoints. Additionally, it implements a custom logging middleware to record request details, providing data support for performance optimization and problem diagnosis.

[0138] In this embodiment, the API interface layer, through the collaborative work of the above three modules, realizes the standardization, security, and monitorability of the national cryptographic algorithm, providing complete interface service support for the deployment of the national cryptographic algorithm in practical applications. At the same time, through the asynchronous characteristics and dependency injection system of FastAPI, the high performance and scalability of the service are ensured.

[0139] In this embodiment, the front-end application layer is the only interface for interaction between the national cryptographic algorithm platform and the user. Figure 1 This layer is clearly identified as the front-end application layer (Vue 3 + Vite), located at the very top of the entire platform, and communicates with the back-end services through the API interface layer. The front-end application layer is built on Vue 3 and Element Plus to create a modern front-end system, achieving a complete user interaction experience through three dimensions: interface design, functionality implementation, and technical architecture.

[0140] 1. Technology Stack Selection: At the front-end application layer, the system uses Vue 3 as the core framework, combined with the Composition API to achieve logic reuse and component-based development. The Vite build tool enables rapid hot reloading and efficient packaging, significantly improving development efficiency. Pinia state management is introduced to replace Vuex for cross-component data sharing, optimizing the state management mechanism. Vue Router is used to implement routing control based on historical APIs, ensuring the modernization and efficiency of the system architecture, which directly corresponds to... Figure 1 The front-end application layer includes the "Route Management (Vue Router)" and "State Management (Pinia)" modules.

[0141] 2. Core Page Implementation: This section details the implementation of the "view components (SM2 / SM3 / SM4 / ZUC)" in the front-end application layer. The login / registration page uses a form component for data verification and integrates the OAuth 2.0 protocol to support single sign-on, providing users with a secure authentication entry point. The key management page uses a table component and pagination controls to display and paginate keys, and combines this with a dialog component to create a key operation interface. This works closely with the "key management" routing in the API interface layer and the "key service" in the business service layer, providing users with intuitive key lifecycle management. The algorithm operation page features independent card-style layouts for SM2, SM3, SM4, and ZUC. Each card includes an input area, an operation area, and a result display area, and integrates data loading animations and operation feedback prompts, ensuring a user-friendly interactive experience when using the various national cryptographic algorithm services provided by the API interface layer.

[0142] 3. Technical Architecture Optimization: In the front-end application layer, a CSS variable system enables theme switching and dark mode support, enhancing the customizability of the user interface. Combining Flexbox and Grid layout ensures responsive adaptation, allowing the platform to provide excellent display effects on different devices. Simultaneously, transition animations and keyframe animations optimize page transitions and component interactions, enhancing the smoothness of the user experience. Internationalization plugins enable multilingual support, expanding the platform's user base. Role-based access control based on the RBAC model dynamically generates sidebar menus and blocks unauthorized access, ensuring system security and user experience. This works in conjunction with the "authentication routing" in the API interface layer and the "user service" in the business service layer, providing comprehensive access management functionality.

[0143] This invention uses commonly available Chinese cryptographic algorithms for speed comparison tests. Through comprehensive performance comparison tests between the proposed Chinese cryptographic algorithm and mainstream libraries such as gmssl and pysmx, the significant optimization effect of the proposed algorithm in multi-dimensional algorithmic scenarios is verified. In the SM2 asymmetric algorithm test, the proposed algorithm, through pre-computation of the base point and a fast dot product algorithm (Montgomery's ladder method), reduced the time taken for 50 random number dot products from 250.59 ms in gmssl to 5.81 ms. Specific performance comparisons are as follows: Figure 4 As shown, the signature and verification processes employ a hybrid coordinate system and sliding window optimization, resulting in a signature time of 0.29 ms, only 4.1% of GMSSL's. Furthermore, the end-to-end key negotiation time is 5.2 ms, a 6-fold improvement over the traditional ECDH protocol (30.82 ms). For a detailed performance comparison, see [link to performance comparison]. Figure 5 and Figure 6 As shown, it meets the high concurrency requirements in most cases. Functional testing further verified the integrity and compatibility of the national cryptographic algorithm in this project: SM2 encryption and decryption successfully restored the standard test vector (the decryption result encryption standard is completely consistent with the SM2 specification), the shared key generated by key negotiation matches the national cryptographic example, and the R value of the digital signature meets the expectations of SM2_A.2.

[0144] In the SM3 hash algorithm test, this project's national cryptographic algorithm, through memory block parallel computing and dynamic preprocessing technology, compressed the hashing time of a long message (1488.4B) from 900.11ms in gmssl to 1.17ms. The accelerated version (mysm3) even reached 0.33% of the traditional library pysmx, and the second hash took only 9.3μs, a 98% reduction compared to the first hash, demonstrating the advantages of JIT compilation and cache reuse. Performance comparison between the first hash and consecutive hashes is shown below. Figure 7 and Figure 8As shown, this fully demonstrates the advantages of JIT compilation and cache reuse. Performance profiling data indicates that SM3's CF function accounts for 97% of the computation time, pointing the way for future optimizations.

[0145] In SM4 encryption and decryption tests, the national cryptographic algorithm in this project optimized the S-box calculation process through Numba just-in-time compilation and combined with pre-computed round key technology, improving the round function execution efficiency by 12 times. In ECB mode, the self-developed acceleration library (mysm4) took only 2.65ms to encrypt a long message (1463.9B), which is 0.72% of gmssl; in CBC mode, the self-developed library accelerated the inter-block XOR operation through vectorized instructions (AVX2), and the decryption time of the long message was 3.43ms, which is 99.4% lower than pysmx, and the initialization time (54.0μs) was only 8.5% of gmssl, making it suitable for high-frequency key switching scenarios. Regardless of the length of the message (such as... Figure 9 (as shown) or SMS (such as) Figure 10 As shown in the figure, the performance of the self-developed acceleration library (mysm4) is better than that of the comparison library.

[0146] In the ZUC stream cipher test, the national cryptographic algorithm in this project uses the SIMD instruction set to optimize the keystream generation logic, compressing the total encryption time of 50 long messages (average 1528.4B) from 628.42ms in pysmx-ZUC to 4.63ms. Furthermore, the single initialization time (8.5μs) is reduced by 96% compared to traditional libraries. The performance comparison results are as follows: Figure 11 As shown, this demonstrates its suitability for low-latency communication in IoT devices.

[0147] This invention proposes a national cryptographic algorithm acceleration platform based on Numba just-in-time compilation technology. By deeply integrating cryptographic mathematical models and dynamic compilation optimization mechanisms, it achieves high-performance optimization of SM2, SM3, SM4, and ZUC algorithms under a general computing architecture. Unlike traditional hardware-dependent acceleration solutions, this platform innovatively applies Numba's LLVM compilation chain to the core modules of national cryptographic algorithms. For computationally intensive operations such as elliptic curve multiplication, hash iteration round functions, and block encryption transformations, it significantly improves algorithm execution efficiency through numerical computation mode reconstruction and instruction-level optimization, while maintaining code maintainability and cross-platform compatibility. In the SM2 asymmetric algorithm, by pre-computing the base point and using a fast multiplication algorithm, the computational overhead of elliptic curve scalar multiplication is significantly reduced, significantly improving the efficiency of signature and verification. It also optimizes the key negotiation process, enabling excellent performance in high-concurrency scenarios. Functional testing further verifies the integrity and compatibility of the algorithms, ensuring they comply with national cryptographic standards and specifications. In the SM3 hash algorithm, the computational efficiency of long message hashing is significantly improved through memory block parallel computing and dynamic preprocessing techniques. Furthermore, the performance of secondary hashing is further optimized through JIT compilation and cache reuse techniques, demonstrating the algorithm's high efficiency and stability. In the SM4 encryption / decryption algorithm, the S-box computation process is optimized through Numba just-in-time compilation, and combined with pre-computation round key technology, significantly improving the efficiency of block encryption. Especially in ECB and CBC modes, it exhibits excellent encryption / decryption performance, suitable for high-frequency key switching scenarios. In the ZUC stream cipher algorithm, the key stream generation logic is optimized using the SIMD instruction set, significantly improving the encryption efficiency of stream ciphers. Simultaneously, the low-latency initialization design makes it suitable for the real-time communication needs of IoT devices. In addition, this invention reduces dependence on specific hardware platforms through transfer learning and hardware adaptation optimization, enhancing the algorithm's versatility and scalability. Experimental results show that this invention exhibits excellent stability and robustness under different data scales and computational scenarios, with significant advantages, particularly in long message processing and high-concurrency scenarios.

[0148] This invention is described with reference to flowchart illustrations and / or block diagrams of methods, apparatus (systems), and computer program products according to embodiments of the invention. It will be understood that each block of the flowchart illustrations and / or block diagrams, and combinations of blocks in the flowchart illustrations and / or block diagrams, can be implemented by computer program instructions. These computer program instructions can be provided to a processor of a general-purpose computer, special-purpose computer, embedded processor, or other programmable data processing apparatus to produce a machine, such that the instructions, which execute via the processor of the computer or other programmable data processing apparatus, generate instructions for implementing the flowchart illustrations and / or block diagrams. Figure 1 One or more processes and / or boxes Figure 1 A device that provides the functions specified in one or more boxes.

[0149] These computer program instructions may also be stored in a computer-readable storage medium that can direct a computer or other programmable data processing device to function in a particular manner, such that the instructions stored in the computer-readable storage medium produce an article of manufacture including instruction means, which are implemented in a process Figure 1 One or more processes and / or boxes Figure 1 The function specified in one or more boxes.

[0150] These computer program instructions may also be loaded onto a computer or other programmable data processing equipment to cause a series of operational steps to be performed on the computer or other programmable equipment to produce a computer-implemented process, thereby providing instructions that execute on the computer or other programmable equipment for implementing the process. Figure 1 One or more processes and / or boxes Figure 1 The steps of the function specified in one or more boxes.

[0151] Specific embodiments have been used to illustrate the principles and implementation methods of this invention. The descriptions of the embodiments above are only for the purpose of helping to understand the method and core ideas of this invention. At the same time, for those skilled in the art, there will be changes in the specific implementation methods and application scope based on the ideas of this invention. Therefore, the content of this specification should not be construed as a limitation of this invention.

[0152] Those skilled in the art will recognize that the embodiments described herein are intended to help the reader understand the principles of the invention, and should be understood that the scope of protection of the invention is not limited to such specific statements and embodiments. Those skilled in the art can make various other specific modifications and combinations based on the technical teachings disclosed in this invention without departing from the spirit of the invention, and these modifications and combinations are still within the scope of protection of this invention.

Claims

1. A national secret algorithm acceleration system based on Numba just-in-time compilation technology, characterized in that, Comprise: A core algorithm layer for reconstructing numerical calculation patterns of SM2 elliptic curve scalar multiplication, SM3 message expansion round function, SM4 nonlinear transformation, and ZUC stream generation logic contained in the core calculation module of the national cryptographic algorithm using the LLVM compilation chain of Numba, converting Python code for interpretation execution into optimized machine code adapted to hardware; And through the njit decorator to achieve key function compilation acceleration, through the compiled scheduling dynamic identification hot operation and load differentiated instruction optimization strategy; Among them, also includes a dynamic compilation scheduling system as the core algorithm layer of the national secret algorithm platform, through the hot function recognition mechanism, the execution process of SM2, SM3, SM4, ZUC and other algorithms in the core algorithm layer is analyzed at runtime performance, using sampling counter and call stack backtracking technology to collect function call frequency, execution time and memory access mode and other performance indicators, and store the data in the performance event buffer, and then through the threshold filtering algorithm Among them And Respectively represent the execution time and call frequency of function f, the expression determines whether function f is a compute-intensive hotspot by judging whether the two indicators simultaneously exceed the preset performance threshold And Total call times And Automatic identification and marking of compute-intensive functions such as SM2 point multiplication operation kG_fast and SM3 compression function CF and other high-frequency calls; The compilation strategy loading mechanism queries the instruction set extensions supported by the CPU through cpuid instruction or / proc / cpuinfo according to the characteristics of the target hardware architecture, constructs a feature vector Each item in the vector is a Boolean flag, which represents whether the CPU supports a specific SIMD instruction set extension; And based on the decision tree model D:F→S, select the optimal compilation parameter set S, generate highly optimized machine code for each algorithm module in the core algorithm layer, and adjust the loop unrolling factor, instruction scheduling strategy and memory alignment parameters according to the processor microarchitecture characteristics; The cache management mechanism maintains a persistent cache pool of JIT compilation results, through function signature hashing as the index key, where {code}(f) represents the source code or byte code of function f, represents the parameter set used at compile time, and || is the concatenation operation, which performs SHA-256 hashing on the combination of the two; the machine code generated by the compilation is stored in a shared memory area or a disk file (.jitcache), supporting cross-process sharing of compiled machine code; A data model layer for mapping the table structure of the underlying database through a key model; A business service layer for implementing key generation, secure storage, distribution rotation, and audit destruction through a key service; An API interface layer for building a RESTful API service layer based on the FastAPI framework, implementing service encapsulation, key management interfaces, and performance monitoring; A front-end application layer for building a front-end system based on Vue 3 and Element Plus, implementing user interaction through interface design, function implementation, and technical architecture.

2. The system for accelerating a national cryptographic algorithm based on the Numba just-in-time compilation technology according to claim 1, characterized in that, The core algorithm layer reconstructs the numerical calculation pattern of SM2 elliptic curve scalar multiplication, including: The parameters are pre-calculated and stored using the pre_kG function. The query matrix, the It is a predefined fixed point on the selected elliptic curve, forming a two-dimensional lookup table of 32 rows × 255 columns, and stored as a binary file SM2_kG.bin; Implementing the Montgomery modular multiplication algorithm using the C extension library _ec_lib, converting operands to the Montgomery domain for calculation, and finally converting back to the normal domain; Performing inverse element pre-computation during SM2 class initialization, Computing and solving wherein, is the modulo operation; Caching results for signature functions ; is the final generated digital signature pair The second key component in is the signer's private key, which is a secret integer is a temporary random number is the temporary point is the first component in the signature pair, is the temporary point's coordinates; and n is the order of the elliptic curve base point ​ Affine coordinate points are mapped as three-dimensional Jacobian coordinates by a Jacobian coordinate system Point addition and doubling operations are implemented in the ec_ws_add and ec_ws_double functions;​​​ Loading and defining function prototypes using ctypes, and loading pre-computed data during ECC_Curve class initialization.

3. The system of claim 1, wherein the system is based on Numba just-in-time compilation technology. The core algorithm layer reconstructs the numerical calculation pattern of the SM3 message expansion round function, including: Using np.frombuffer to create an array directly from a byte stream, applying the @njit decorator to the compression function CF (Compression Function) and auxiliary function i8_u4 for static compilation, converting Python dynamic type code to LLVM (Low Level Virtual Machine) intermediate representation; Involving Boolean function operations, converting branch judgments to bit operation expressions; using Numpy's uint32 type array to ensure that state variables are stored continuously in memory, providing support for branch-free vectorized (SIMD) parallel computing for JIT (Just-in-Time) compilers; and preloading round constants while directly compiling loop left shift bit operations as efficient CPU native instructions.

4. The system for accelerating a national cryptographic algorithm based on the Numba just-in-time compilation technology according to claim 1, characterized in that, The core algorithm layer reconstructs the numerical calculation pattern of the SM4 nonlinear transformation, including: Extending the 8-bit S-box to a 16-bit pre-computed lookup table by pre-computing and storing all possible 16-bit input value replacement results; Using the @njit(parallel=True) decorator and prange parallel iterator to implement data block-level parallel encryption in ECB (Electronic Codebook) mode; performing multi-threaded parallel processing of independent data blocks during encryption, and combining cache-friendly block strategies to optimize the processing throughput of large amounts of data; Using compilation optimization techniques such as loop unrolling and register reuse to compile the core linear transformation function into a branch-free vectorized (SIMD) instruction sequence; In-place state update technique is adopted to reduce memory copy overhead, and thread-local storage is used to pre-allocate round key buffer safely to support high concurrency encryption and decryption. The core calculation logic in the round function is reconstructed to combine independent nonlinear byte substitution and linear diffusion transformation into a single composite algebraic operation, aiming to reduce function call overhead and intermediate result access times. All system parameters and round constants required in the encryption process are pre-computed and cached.

5. The Numba just-in-time compilation technology-based SM algorithm acceleration system according to claim 1, characterized in that, The numerical calculation mode reconstruction of ZUC stream generation logic in the core algorithm layer includes: The conditional bit shift operation in the core state update is reconstructed as a branchless arithmetic shift combined with a mask, and the modulo reduction operation is combined through continuous bit operations to eliminate branch prediction overhead. The linear transformation and nonlinear S-box lookup in the bit reorganization are split into independent pipeline stages, and a pure arithmetic logic unit (ALU) instruction sequence is generated through multi-level shift XOR logic, while the lookup operation is optimized to an efficient register load using pre-computation and constant folding techniques. Through the forced inline optimization of the JIT compiler, the call overhead of the core state update function is eliminated, and the state variables of the linear feedback shift register (LFSR) are directly mapped to the register operation, while the zero-copy technology is used to create a data view to avoid memory copying. Through loop unrolling and software pipelining technology, the state update and key generation operations of 4 consecutive rounds are overlapped and executed. For the extension mode of ZUC-256, the advanced vector extension instruction set (AVX2) is used to process multiple 32-bit words simultaneously, realizing parallel processing based on SIMD instructions.

6. The system for accelerating a national secret algorithm based on the Numba just-in-time compilation technology according to claim 1, characterized in that, The core algorithm layer dynamically identifies hot operations and loads differentiated instruction optimization strategies through compilation scheduling, including: Through the hot function identification mechanism, the algorithm core module is analyzed for runtime performance. Sampling and call stack analysis are used to collect function call frequency and execution time key performance indicators, and performance data is filtered based on pre-set thresholds to automatically identify and mark the most computationally intensive function modules. The compilation strategy dynamic loading mechanism first identifies the instruction set architecture supported by the processor through hardware feature detection, then selects the optimal compilation optimization parameter set for the identified hot functions based on a decision model, and finally generates machine code adapted to the current hardware. According to the specific microarchitecture, the instruction scheduling and memory access strategy are fine-tuned. The compilation result cache management mechanism stores the generated machine code in a persistent cache pool by maintaining a persistent cache pool, and uses the hash value based on the function signature as the unique identifier for indexing. At the same time, the system uses the LRU cache replacement strategy to dynamically manage the cache pool to optimize storage efficiency.

7. The system for accelerating a national encryption algorithm based on the Numba just-in-time compilation technology according to claim 1, characterized in that, The data model layer maps the underlying database table structure through the key model, including: Key multi-level encryption storage is implemented based on the SQLAlchemy ORM layer, which maps the underlying database table structure by defining the KeyModel data model. During the persistence process, the system uses the national cryptographic algorithm to encrypt the key data, and this encryption process is transparent to the upper layer application. Moreover, the key used to encrypt the key is derived from the user's master key through a password-based key derivation function, and the atomicity of the entire storage process is guaranteed by the database transaction mechanism.

8. The system for accelerating a national secret algorithm based on the Numba just-in-time compilation technology according to claim 1, characterized in that, The business service layer implements key generation, secure storage, distribution rotation, and audit destruction through the key service, including: A hardware entropy source-based true random number generator (TRNG) is accelerated using JIT compilation technology to generate high-entropy keys quickly. This process involves sampling and randomness post-processing of raw physical noise, real-time entropy evaluation based on NIST SP 800-90B standards, and ensuring that the final output random number meets the cryptographic security requirements. The key material is securely distributed and packaged through the national asymmetric encryption protocol, and the key is periodically rotated using an automated life cycle management strategy based on time and usage frequency. The version control mechanism ensures smooth transition of the business. An unforgeable audit log based on a cryptographic hash chain is constructed to track and record the entire life cycle of the key. During the key destruction phase, strict security destruction procedures are followed, including using professional instructions to overwrite the storage area and forcibly clearing the memory residue to prevent key information from being recovered.

9. The system for accelerating a national secret algorithm based on the Numba just-in-time compilation technology according to claim 1, characterized in that, The API interface layer is built based on the FastAPI framework to implement the RESTful API service layer, including service encapsulation, key management interface, and performance monitoring. Standardized endpoints are used, and each endpoint strictly validates input parameters through request models. Interface authentication is achieved using a dependency injection system, and encryption requests are processed using asynchronous processors. The decoupling of underlying algorithm implementation and HTTP interface achieves a high-cohesion and low-coupling service architecture. The key life cycle management API is used to implement permission management through fine-grained role-based access control. Key operation permission enumeration is defined, and interface-level permission control is achieved using middleware. Database transactions ensure the atomicity of key operations, supporting secure key generation, storage, rotation, and revocation. Performance monitoring is embedded, and monitoring support is provided to the front-end application layer and the business service layer and core algorithm layer. A Prometheus metrics expositor is built-in, and monitoring code is injected through middleware. Key performance indicators are defined, and real-time data is collected and exposed through dedicated endpoints. A custom log middleware records request details.

10. The system for accelerating a national cryptographic algorithm based on the Numba just-in-time compilation technology according to claim 1, characterized in that, The front-end application layer is built based on Vue 3 and Element Plus to implement user interaction through interface design, function implementation, and technical architecture. It adopts Vue 3 as the core framework, combined with the Composition API to achieve logic reuse and component-based development; it uses the Vite build tool to achieve fast hot reloading and efficient packaging; it introduces Pinia state management to replace Vuex to achieve cross-component data sharing and optimize the state management mechanism; and it uses Vue Router to implement routing control based on historical APIs. On the key management page, the key display and pagination functions are implemented through table components and pagination controls, and the key operation interface is implemented in combination with dialog components; on the algorithm operation page, independent card layouts are designed for SM2, SM3, SM4 and ZUC respectively. Each card contains an input area, an operation area and a result display area, and integrates data loading animation and operation feedback prompts. Theme switching and dark mode support are achieved through a CSS variable system, and responsive adaptation is ensured by combining Flex layout and Grid layout. At the same time, transition animations and keyframe animations are introduced to optimize page switching and component interaction, and multi-language support is achieved through an internationalization plugin. Role-based access control is implemented based on the RBAC model, and sidebar menus are dynamically generated and unauthorized access is blocked.

Citation Information

Patent Citations

  • Method and device for determining hotspot function, electronic equipment and storage medium

    CN117075905A