National cryptographic algorithm acceleration system based on Numba just-in-time compiling technology

The core module of the Guomi algorithm is reconstructed through Numba instant compilation technology, which solves the performance bottlenecks and maintainability problems of Guomi algorithm in dynamic environments, and realizes efficient and flexible Guomi algorithm acceleration, supporting cross-platform deployment and engineering application of post-quantum cryptography algorithms.

CN120560665AActive Publication Date: 2025-08-29SOUTHWEST PETROLEUM UNIV
View PDF 5 Cites 0 Cited by

Patent Information

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

AI Technical Summary

Technical Problem

The existing Guomin algorithms are difficult to adapt to dynamic changes in cloud computing and edge computing environments, and the hardware acceleration solutions are highly closed. Traditional optimization leads to poor maintainability, static compilation affects code auditability, and post-quantum cryptographic algorithms are not engineered enough to cope with quantum computing security challenges.

Method used

Using Numba instant compilation technology, the core computing module of the Guoxin algorithm is reconstructed through the LLVM compilation chain, combined with the @njit decorator to achieve function compilation acceleration, dynamically identify hotspot operations and load differentiated instructions to optimize, build a hierarchical architecture, provide standardized API interfaces, and support cross-platform deployment and rapid iteration.

Benefits of technology

It realizes high-performance optimization of Guomi algorithm under the general computing architecture, maintains code maintainability and cross-platform compatibility, significantly improves algorithm execution efficiency, reduces integration complexity, and supports plug-and-play acceleration of post-quantum cryptography algorithms.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN120560665A_ABST
    Figure CN120560665A_ABST
Patent Text Reader

Abstract

The invention relates to the technical field of national cryptographic algorithm acceleration, and discloses a national cryptographic algorithm acceleration system based on a Numba just-in-time compiling technology. The numerical calculation mode reconstruction module is used for performing numerical calculation mode reconstruction on SM2 elliptic curve scalar multiplication, SM3 message extension round function, SM4 nonlinear transformation and ZUC flow generation logic contained in the national cryptographic algorithm core calculation module by utilizing an LLVM compiling chain of Numba, and converting an interpretively executed Python code into an optimized machine code adaptive to hardware; key function compiling acceleration is achieved through a (at) njit decorator, hot spot operation is dynamically recognized through compiling scheduling, and a differential instruction optimization strategy is loaded; the platform shows multiple technical advantages: on the development efficiency level, by presetting a standardized acceleration module library and an automatic compiling tool chain, the integration complexity of a national cryptographic algorithm is greatly reduced; in the aspect of operation performance, the compilation optimization depth is better than that of a general interpreter acceleration scheme; in the aspect of safety controllability, the mathematical theory basis of the national cryptographic 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] The present invention relates to the field of national secret algorithm acceleration technology, and in particular to a national secret algorithm acceleration system based on Numba just-in-time compilation technology. Background Art

[0002] Existing technology approaches are mired in multiple dilemmas: hardware acceleration solutions are constrained by the closed ecosystem of specialized chips, making them difficult to adapt to dynamic environments like cloud computing and edge computing. Traditional optimizations based on low-level languages ​​require deep involvement in underlying implementations, compromising algorithm maintainability. Static compilation techniques sacrifice code auditability for limited performance gains, making them incapable of passing cryptographic module security reviews. While distributed architectures alleviate throughput pressures through horizontal scaling, they cannot overcome the physical limits of single-node execution efficiency. Furthermore, the engineering preparation for post-quantum cryptographic algorithms is insufficient, and the existing national cryptography system suffers from generational gaps in algorithm agility and cross-platform deployment capabilities, making it difficult to meet the security challenges of the quantum computing era.

[0003] In this context, it is urgent to build a new generation of national secret algorithm engineering technology system. On the premise of ensuring the correctness and compliance of cryptography, it is necessary to break through performance bottlenecks, reduce integration complexity, strengthen key security management, and optimize human-computer interaction experience, so as to promote domestic cryptographic technology from standard setting to in-depth development of the industry, and lay a solid security foundation for the construction of Digital China. Summary of the Invention

[0004] To address the aforementioned shortcomings in the existing technology, the present invention provides a national cryptographic algorithm acceleration system based on Numba's just-in-time compilation technology. By deeply integrating cryptographic mathematical models with dynamic compilation optimization mechanisms, this system achieves both high performance and maintainability. Its core innovation lies in leveraging Numba's LLVM compilation chain to reconstruct the numerical computation model of the core computational modules of the national cryptographic algorithm (including SM2 elliptic curve scalar multiplication, SM3 message expansion round function, SM4 nonlinear transformation, and ZUC stream generation logic). This system converts the interpreted Python code into hardware-optimized machine code, thus overcoming performance bottlenecks while maintaining code readability. The platform utilizes a layered architecture. The algorithm kernel layer accelerates the compilation of key functions using the @njit decorator. The compilation and scheduling layer dynamically identifies hot operations and loads differentiated instruction optimization strategies. The service interface layer provides a standardized API for seamless integration with existing cryptographic service systems. Compared to hardware acceleration solutions, this platform avoids reliance on specialized instruction sets, achieving balanced performance across x86 and ARM architectures. Compared to static compilation techniques, it maintains complete code auditability and supports rapid algorithm iteration and upgrades. Addressing the efficiency deficiencies of pure Python implementations, the platform uses just-in-time compilation technology to improve the performance of key operations several times. Furthermore, the platform comes pre-installed with a library of acceleration modules certified by the National Cryptography Administration. Developers can access acceleration capabilities through simple interface calls without in-depth understanding of compilation principles, significantly reducing integration complexity and providing a high-performance, highly flexible engineering foundation for building a national cryptography algorithm ecosystem.

[0005] In order to achieve the above-mentioned object of the invention, the technical solution adopted by the present invention is: A national cryptographic algorithm acceleration system based on Numba just-in-time compilation technology, including: The core algorithm layer is used to use Numba's LLVM compilation chain to reconstruct the numerical calculation model of the SM2 elliptic curve scalar multiplication, SM3 message expansion round function, SM4 nonlinear transformation and ZUC flow generation logic included in the core calculation module of the national secret algorithm, convert the interpreted Python code into hardware-adapted optimized machine code; and realize key function compilation acceleration through the @njit decorator, dynamically identify hot operations through compilation scheduling and load differentiated instruction optimization strategies; The data model layer is used to map the underlying database table structure through the key model; The business service layer is used to implement key generation, secure storage, distribution rotation, and audit destruction through key services; The API interface layer is used to build a RESTful API service layer based on the FastAPI framework to implement service encapsulation, key management interface and performance monitoring; The front-end application layer is used to build the front-end system based on Vue 3 and Element Plus, and realize user interaction through interface design, function implementation and technical architecture.

[0006] Furthermore, the core algorithm layer reconstructs the numerical calculation mode of SM2 elliptic curve scalar multiplication, including: Pre-calculate and store parameters through the pre_kG function The query matrix, It is a fixed point pre-defined 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; The C extension library _ec_lib is used to implement the Montgomery modular multiplication algorithm, converting the operands to the Montgomery domain for calculation and then converting them back to the normal domain. Perform inverse element pre-calculation when the SM2 class is initialized, calculate And solve , is the remainder operation, Using result cache for signature functions ; The final generated digital signature pair The second key component in; is the signer's private key, is a secret integer; It is a temporary random number; is the first component of the signature pair, It's a temporary one coordinates; and n is the base point of the elliptic curve of order; Use the Jacobi coordinate system to transform the affine coordinate points Mapped to three-dimensional Jacobian coordinates , , described ; Implement point addition and point doubling operations in the ec_ws_add and ec_ws_double functions; Use ctypes to load and define function prototypes, and load precalculated data when the ECC_Curve class is initialized.

[0007] Furthermore, the core algorithm layer reconstructs the numerical calculation mode of the SM3 message extension round function, including: Use np.frombuffer to create an array directly from a byte stream. Apply the @njit decorator to statically compile the compression function CF (Compression Function) and the auxiliary function i8_u4, converting Python dynamic type code into LLVM (Low Level Virtual Machine) intermediate representation; The Boolean function operations involved convert branch judgments into bitwise operation expressions; Numpy's uint32 type array is used to ensure that state variables are stored continuously in memory, providing support for branchless vectorization (SIMD) parallel computing enabled by the JIT (Just-in-Time) compiler; and round constants are preloaded, while bitwise operations such as circular left shift are directly compiled into efficient CPU native instructions.

[0008] Furthermore, the core algorithm layer reconstructs the numerical calculation mode of SM4 nonlinear transformation, including: Expand the 8-bit S-box into a 16-bit pre-computed lookup table by pre-computing and storing the replacement results corresponding to all possible 16-bit input values; Implement block-level parallel encryption in Electronic Codebook (ECB) mode using the @njit(parallel=True) decorator and the prange parallel iterator. Multithreaded parallel processing of independent data blocks during encryption is combined with a cache-friendly chunking strategy to optimize throughput for large data volumes. Through loop unrolling and register reuse compilation optimization technology, the core linear transformation function is compiled into a branchless vectorized (SIMD) instruction sequence; Adopt in-place state update technology to reduce memory copy overhead, and securely pre-allocate round key buffers through thread-local storage to support high-concurrency encryption and decryption; The core computational logic within the round function is restructured to combine the independent nonlinear byte replacement and linear diffusion transformation into a single composite algebraic operation, aiming to reduce function call overhead and the number of accesses to intermediate results. Precompute and cache all system parameters and round constants required for the encryption process.

[0009] Furthermore, the core algorithm layer reconstructs the numerical calculation mode of the ZUC flow generation logic, including: Refactor the conditional shift operations in core state updates into branchless arithmetic shifts combined with masks, and merge the modular reduction operations with consecutive bitwise operations to eliminate branch prediction overhead; The linear transformation and nonlinear S-box table lookup in bit reorganization are separated into independent pipeline stages. A pure arithmetic logic unit (ALU) instruction sequence is generated through multi-stage shift XOR logic. Pre-computation and constant folding techniques are used to optimize the table lookup operation into an efficient register load. Through 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 register operations. At the same time, zero-copy technology is combined to create data views to avoid memory copying; By using loop unrolling and software pipelining techniques, four consecutive rounds of state updates and key generation operations are overlapped. The extended mode of ZUC-256 uses the Advanced Vector Extensions (AVX2) instruction set to process multiple 32-bit words simultaneously, realizing parallel processing based on SIMD instructions.

[0010] Furthermore, the core algorithm layer dynamically identifies hotspot operations through compilation and scheduling and loads differentiated instruction optimization strategies, including: Through the hot function identification mechanism, the runtime performance of the algorithm core module is analyzed. Sampling and call stack analysis are used to collect key performance indicators such as function call frequency and execution time. By filtering the performance data based on preset thresholds, the most computationally intensive function modules are automatically identified and marked. A dynamic compilation policy loading mechanism is used. This mechanism first identifies the instruction set architecture supported by the processor through hardware feature detection. It then uses a decision model to select the optimal compilation optimization parameter set for the identified hotspot functions, ultimately generating machine code adapted to the current hardware. It then fine-tunes instruction scheduling and memory access strategies based on the specific microarchitecture. A cache management mechanism for compilation results is adopted, which maintains a persistent cache pool to store the compiled machine code and uses the hash value based on the function signature as a 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.

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

[0012] Furthermore, the business service layer uses key services to implement key generation, secure storage, distribution rotation, and audit destruction, including: Using JIT compilation technology to accelerate a hardware-based true random number generator (TRNG) to achieve rapid high-entropy key generation. This process samples and post-processes the raw physical noise for randomness, and performs real-time entropy evaluation according to the NIST SP800-90B standard to ensure that the final random number output meets cryptographic security requirements. The secure distribution and packaging of key materials are achieved through the national secret asymmetric encryption protocol. Keys are regularly rotated using an automated lifecycle management strategy based on time and frequency of use, ensuring a smooth transition of services through a version control mechanism. By building an unalterable audit log based on a cryptographic hash chain, the entire life cycle of the key is tracked and recorded. During the key destruction phase, strict security destruction procedures are followed, including using professional instructions to overwrite the storage area and forcibly clearing memory residues to prevent key information from being recovered.

[0013] Furthermore, the API interface layer builds a RESTful API service layer based on the FastAPI framework to implement service encapsulation, key management interface and performance monitoring, including: Standardized endpoints are used, each of which strictly verifies input parameters through the request model. A dependency injection system is used to implement interface authentication. Encrypted requests are processed through asynchronous processors, and the underlying algorithm implementation is decoupled from the HTTP interface, achieving a highly cohesive and low-coupling service architecture. The key lifecycle management API is used to implement permission management through fine-grained role-based access control. It defines key operation permission enumeration and implements interface-level permission control in combination with middleware. At the same time, the atomicity of key operations is ensured through database transactions, supporting the secure generation, storage, rotation, and revocation of keys. It has built-in performance monitoring capabilities and provides monitoring support to the front-end application layer, business service layer, and core algorithm layer. It also has a built-in Prometheus indicator exposer that injects monitoring code through middleware, defines key performance indicators, collects operating data in real time, and exposes monitoring indicators through dedicated endpoints. It also has a custom log middleware that records request details.

[0014] Furthermore, the front-end application layer builds a front-end system based on Vue 3 and Element Plus, and implements user interaction through interface design, function implementation and technical architecture, including: Using Vue 3 as the core framework, combined with the Composition API to achieve logic reuse and component-based development; using the Vite build tool to achieve fast hot reload and efficient packaging; introducing Pinia state management instead of Vuex to achieve cross-component data sharing and optimize the state management mechanism; using Vue Router to implement routing control based on the history API; On the key management page, table components and paging controls are used to display and paginate keys, 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. Each card contains an input area, an operation area, and a result display area, and integrates data loading animations and operation feedback prompts. Theme switching and dark mode support are achieved through the CSS variable system, and responsive adaptation is ensured by combining Flex layout and Grid layout. At the same time, transition animation and keyframe animation are introduced to optimize page switching and component interaction, and multi-language support is achieved through internationalization plug-ins. Role permission control is implemented based on the RBAC model, sidebar menus are dynamically generated, and illegal access is blocked.

[0015] The present invention has the following beneficial effects: The platform constructed by the present invention, based on the Numba library, achieves high-performance optimization of national cryptographic algorithms on general-purpose computing architectures through the deep integration of just-in-time 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 point multiplication, hash round functions, and block encryption transformations, this platform significantly improves algorithm execution efficiency through numerical computation model reconstruction and instruction-level optimization, while maintaining code maintainability and cross-platform compatibility. The platform also proposes a dynamic hotspot function compilation mechanism that automatically identifies critical computation 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 model, this solution overcomes the performance bottleneck of interpreted languages ​​in cryptographic computations while avoiding the complex development of C / C++ extensions, providing a lightweight transformation path for algorithm iteration and upgrades. Compared with mainstream acceleration solutions, this platform demonstrates multiple technical advantages: In terms of development efficiency, it significantly reduces the integration complexity of national cryptographic algorithms through a pre-built standardized acceleration module library and automated compilation toolchain; in terms of operational 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 foundations of national cryptographic algorithms, avoiding the hidden risks that may be introduced by black-box hardware acceleration. The platform's architecture design offers forward-looking scalability, supporting plug-and-play acceleration of post-quantum cryptographic algorithms through a modular compilation interface. Experimental verification has shown that this technology 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 driving the in-depth development of the national cryptographic algorithm ecosystem towards high performance and high maintainability. BRIEF DESCRIPTION OF THE DRAWINGS

[0016] Figure 1 This is the overall framework diagram of the national encryption algorithm platform.

[0017] Figure 2 This is a diagram of the API interface document.

[0018] Figure 3 It is a database model relationship diagram.

[0019] Figure 4 This is a comparison chart of SM2 dot multiplication performance.

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

[0021] Figure 6 This is a comparison chart of SM2 signing / verification performance.

[0022] Figure 7This is the SM3Hash performance comparison (first hash) chart.

[0023] Figure 8 This is the SM3Hash performance comparison (continuous hashing) chart.

[0024] Figure 9 This is a comparison chart of SM4 long message performance.

[0025] Figure 10 This is a comparison chart of SM4 short message performance.

[0026] Figure 11 This is a performance comparison chart of ZUC stream cipher. DETAILED DESCRIPTION

[0027] The specific embodiments of the present invention are described below to facilitate understanding of the present invention by those skilled in the art. However, it should be clear that the present invention is not limited to the scope of the specific embodiments. For those skilled in the art, as long as various changes are within the spirit and scope of the present invention as defined and determined by the appended claims, these changes are obvious, and all inventions and creations utilizing the concepts of the present invention are protected.

[0028] The comprehensive national secret algorithm platform constructed by this invention achieves three core breakthroughs:

[0029] First, we perform instruction-level optimization on the core code of the SM2 / SM3 / SM4 / ZUC algorithms based on Numba JIT just-in-time compilation technology.

[0030] Secondly, a full-process key lifecycle management system is designed to implement trusted management and control of the entire chain of key generation, storage, distribution, rotation, and destruction.

[0031] Finally, a minimalist design philosophy was employed to develop an interactive interface, integrating a visual policy configuration engine with automated deployment tools, and combining it with a unified RESTful API service to reduce algorithm integration cycles from weeks to hours. Through three-dimensional innovations—accelerated performance, enhanced management, and an upgraded user experience—the platform has built a comprehensive technology ecosystem covering the entire cryptographic service chain.

[0032] This paper proposes a national secret algorithm acceleration platform based on Numba just-in-time compilation technology, which deeply optimizes the core computing modules of the SM2 / SM3 / SM4 / ZUC algorithms. By reconstructing the computationally intensive functions in the algorithm into a Numba-compatible numerical calculation mode and utilizing its LLVM compiler to generate highly optimized machine code, the performance bottleneck of Python's native interpreted execution is broken through. The platform establishes an algorithm hotspot function registration mechanism, automatically identifies key computing paths such as signature verification, hash iteration, and group encryption, and dynamically loads Numba JIT compilation acceleration modules to significantly improve algorithm execution efficiency. In the key management link, the system implements a multi-level key storage architecture through ORM technology, and builds a secure distribution channel in combination with the national secret protocol to form a full lifecycle management system covering generation, storage, and rotation. The front-end builds a visual console based on a componentized framework, providing algorithm acceleration ratio monitoring and key policy configuration functions. The back-end encapsulates the accelerated national secret service through a standardized RESTful interface, supports elastic deployment and high-concurrency calls in a cloud-native environment, and builds 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, this platform utilizes Numba just-in-time compilation technology to convert the core SM2 / SM3 / SM4 / ZUC algorithms into LLVM-optimized machine code, maintaining code maintainability while breaking performance bottlenecks. Compared to native Python implementations, signature verification speed is increased by 5-8 times, without relying on C / C++ extension development, significantly reducing algorithm optimization complexity. 2) The overall framework is based on a rigorous mathematical foundation (such as SM2 elliptic curve parameter constraints) based on national cryptographic algorithm standards, while the core acceleration module utilizes Numba dynamic compilation technology, achieving the dual advantages of "mathematical verifiability and engineering high performance." Compared to traditional hardware-only acceleration solutions, this platform balances cross-platform deployment flexibility and computational efficiency while ensuring cryptographic correctness. 3) It includes a pre-optimized Numba JIT algorithm module library, certified by the National Cryptography Administration. Compared to proprietary compiler solutions, developers can access acceleration capabilities by simply calling standardized interfaces without having to reimplement underlying algorithm logic, shortening integration cycles by over 70%. The platform also provides algorithm hotspot analysis tools to support fine-tuning and optimization for specific business scenarios.

[0033] 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, including:

[0034] The core algorithm layer is used to use Numba's LLVM compilation chain to reconstruct the numerical calculation model of the SM2 elliptic curve scalar multiplication, SM3 message expansion round function, SM4 nonlinear transformation and ZUC flow generation logic included in the core calculation module of the national secret algorithm, convert the interpreted Python code into hardware-adapted optimized machine code; and realize key function compilation acceleration through the @njit decorator, dynamically identify hot operations through compilation scheduling and load differentiated instruction optimization strategies;

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

[0036] The business service layer is used to implement key generation, secure storage, distribution rotation, and audit destruction through key services;

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

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

[0039] This embodiment constructs a core acceleration engine for the national encryption algorithm through the core algorithm layer.

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

[0041] 1. Base point pre-calculation and fast table lookup: Pre-calculate and construct a 32-row × 255-column two-dimensional lookup table through pre_kG and save it as a binary file SM2_kG.bin. The row index i (from 0 to 31) of the table corresponds to the byte position of the 256-bit scalar k, and the column index j (from 1 to 255) corresponds to all possible non-zero values ​​of a byte. Each table entry Table[i][j] stores the pre-calculated point .

[0042] In the implementation of the ECC_Curve.kG_fast method, the input 256-bit scalar Treated as a 32-byte array, the system traverses this array and for each byte Find the pre-calculated point in its corresponding row i Finally, the 32 points found are accumulated through elliptic curve point addition to obtain the final result R. Through this method, a complete 256-bit scalar multiplication operation is optimized from the original O(n) complexity of hundreds of point additions and point multiplication operations to only 31 point additions and 32 table lookups, greatly improving computational efficiency.

[0043] 2. Modular multiplication and reduction optimization: Use the C extension library _ec_lib to implement the Montgomery modular multiplication algorithm, convert the operands to the Montgomery domain for calculation, and finally convert them back to the normal domain. A special form of , which implements a fast reduction algorithm, Convert to The core of this is to use the prime numbers in the SM2 national encryption standard The special structure of circumvents the high-cost division operation. Represents a large integer to be reduced modulo. and Represent the lower 256 bits and upper 256 bits of the operand T to be reduced, thereby avoiding expensive division operations.

[0044] 3. Inverse element pre-computation during the signing process: Inverse element pre-computation is performed when the SM2 class is initialized.

[0045] calculate And solve , It is a modulo operation to ensure that the final value also falls within the range of 0 to n-1; Using result cache for signature functions ,in The final generated digital signature pair The second key component in this expression represents the signer's private key, is a secret integer; It is a temporary random number generated during each signing process that must be kept confidential; It is the first component of a signature pair, usually along with the 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 over the integer ring modulo n.

[0046] 4. Modulus inverse optimization in point operations: Use Jacobi coordinate system to avoid modular inverse operation in every point operation. In this mode, affine coordinate points Projected into three-dimensional Jacobian coordinates , the two satisfy the conversion relationship and .

[0047] Point addition and doubling operations are implemented in the ec_ws_add and ec_ws_double functions, and a modular inversion is performed only once when affine coordinates are ultimately needed.

[0048] 5. Core operation library integration: Implement core operations through the compiled ecc.pyd library. Use ctypes to load and define function prototypes, and load pre-calculated data when initializing the ECC_Curve class.

[0049] For SM3 hash iteration acceleration, the optimization focus is on improving the computational performance of hash iteration, which is mainly achieved through NumbaJIT compilation technology and memory access optimization.

[0050] 1. Numba JIT compilation and static compilation: Apply the @njit decorator to statically compile the compression function CF and the auxiliary function i8_u4. This converts Python dynamically typed code into LLVM intermediate representation. After multiple levels of optimization, including type inference, inline expansion, loop optimization, and vectorization, efficient machine code is generated. This eliminates interpreter overhead and Global Interval Lock (GIL) restrictions, bringing function execution speeds close to C language levels.

[0051] 2. Pre-calculated constant table and initial vector hard coding: Pre-calculated constants , shift the loop left Solidify to table lookup access and hardcode the initial vector . Reduce repeated calculations at runtime.

[0052] 3. Numpy array and memory alignment optimization: Use Numpy's uint32 type array to continuously store intermediate states, including message extension arrays and Ensure memory alignment and cache prefetch efficiency, reducing the L1 cache miss rate to below 5%.

[0053] 4. Bitwise operations simplify branches and register operations: The bitwise operation j & 0x30 replaces the j ≥ 16 check, and intermediate variables are mapped to register operations. This expression exploits the bit distribution of round number j—the result is zero when j is in the range [0, 15] and non-zero when it is in the range [16, 63]—to transform expensive conditional branches into branchless, single-cycle arithmetic logic. This microarchitectural optimization, combined with mapping intermediate variables to register operations, significantly improves instruction pipeline execution efficiency. Performance profiling has verified that the CPU pipeline prediction failure rate can be reduced to 1.2%, and the proportion of memory read and write instructions can be reduced to 12%.

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

[0055] 6. Boolean function condition optimization: Boolean function in 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 would introduce conditional branches in a direct implementation. Converting branch decisions to bitwise expressions reduces the performance penalty of branch prediction failures. Although the current implementation does not explicitly enable prange multithreading parallelism and @guvectorize vectorization instructions, the performance penalty of branch prediction failures is reduced.

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

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

[0058] pass Precompute and store the replacement results for all possible 16-bit input values, where 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 a 16-bit precomputed lookup table, where 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 replaces two byte table lookups with a single memory access and optimizes a 32-bit word replacement from four memory accesses to just two, significantly reducing memory access latency and cache miss rates.

[0059] 2. Block-level parallel encryption: Use the @njit(parallel=True) decorator and the prange parallel iterator to implement block-level parallel encryption in ECB mode. Divide the input data into 128-bit (16-byte) blocks. pass This method implements multi-threaded parallel processing. Secondly, to collaboratively optimize memory access performance, the method incorporates cache blocking technology. The core of this technology is to leverage the CPU's internal cache hierarchy: the L1 cache (first level cache), which is the smallest but fastest memory and serves as the first stop for CPU data access; and the L2 cache (second level cache), which is larger and slightly slower, but still far superior to main memory. Combined with loop blocking technology, large data sets are divided into sub-blocks sized appropriately for the L1 / L2 cache, ensuring cache line alignment and optimized locality, thereby improving the instruction throughput of multi-core CPUs.

[0060] 3. Round key generation 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. Its cryptographic design objective is to propagate small changes in the input data across the entire 32-bit output word through a series of bitwise exclusive OR (XOR) and circular left shift operations, thereby enhancing the algorithm's resistance to attacks such as differential analysis. The AVX2 instruction set's vpxor, vpsll, and vpsrl instructions are used to implement parallel bitwise operations, eliminating conditional jump overhead and branch misprediction penalties.

[0061] 4. In-place state update and zero-copy memory view: Using in-place state update technology, Directly modify the original array content instead of creating a new array.

[0062] Combined with the zero-copy memory view np.frombuffer(data, dtype=np.uint32).view(np.uint32) , data copying and type conversion overhead are avoided. Pre-allocating the round key buffer through thread-local storage reduces multi-thread contention and synchronization overhead.

[0063] 5. Reconstruction of the round function algorithm: round function The synthetic permutation T in the algorithm is reconstructed, where to are the four 32-bit state words that make up the 128-bit data block, rk is the 32-bit subkey used in this round, and ⊕ represents a bitwise exclusive-or operation. T is the core synthetic permutation function in the round function, which is a single operation reconstructed by combining the nonlinear transformation τ with the linear transformation L'.

[0064] The nonlinear transformation

[0065] With linear transformation Merge into a single operation, reduce the storage and loading of intermediate results, reduce register pressure and memory access times. Decompose a 32-bit input word A into four 8-bit bytes ( to ), and applies a standard 8-bit S-box (S_box) to each byte in parallel for nonlinear replacement. The linear transformation L' function is to shift the input word B to its left by different bits. The subsequent versions are XORed to achieve linear diffusion of data.

[0066] 6. Precalculation of system parameters and wheel constants: Precalculation of system parameters and wheel constants . Avoids repeated calculations during the encryption process.

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

[0068] 1. LFSR state machine update optimization: refactor the 31-bit conditional shift operation into a branchless arithmetic shift-mask combination expression.

[0069] Conditional jump mispredictions are eliminated.

[0070] Through continuous bit operations Merge Modulo Reduction Operations , which enables the LLVM compiler to generate efficient rotl / rotr rotation instructions.

[0071] Where x and y are 31-bit status words; & 0x7FFFFFFF is a bit mask used to extract the low-order 31 bits of the 32-bit addition result, and ≫ 31 is an arithmetic right shift operation used to capture possible overflow bits; adding the two together yields the equivalent modular reduction result.

[0072] 2. Nonlinear filtering stage optimization: The linear transformation of bit reshuffling (BR) and the S-box lookup are separated into independent pipeline stages. The former generates pure ALU instruction sequences (such as AVX512's vpternlog instruction) through a multi-stage shift-XOR chain. The latter utilizes pre-computed two-byte S-boxes. and Implement constant folding and convert table lookup operations Compiles to a direct register load (mov instruction), where S0(X) represents a nonlinear replacement of the 16-bit input word X. ≫8 and &0xFF are bitwise operations used to extract the upper and lower eight bits of X, respectively. The result is used as an index into a precomputed two-dimensional lookup table, _ZUC_S0, decomposing the 16-bit table lookup into two efficient and cache-friendly 8-bit indexed memory accesses. Memory alignment triggers the CPU cache prefetch mechanism, boosting the L1 cache hit rate to near saturation (>99%).

[0073] 3. Function Inlining and Register Operations: Numba's @njit decorator is used to force inlining of the lfsr_next function. This eliminates the function call stack overhead and maps the LFSR state variables to register operations. This is combined with zero-copy data conversion using np.frombuffer(data, dtype=np.uint8).view(np.uint32) to minimize memory accesses.

[0074] 4. Keystream generation function optimization: Through loop unrolling and software pipelining, four consecutive rounds of state updates are overlapped with key generation operations. This fully utilizes the superscalar execution capabilities of modern CPUs and improves instruction-level parallelism.

[0075] 5. SIMD instruction parallel processing: For the ZUC-256 extended mode, SIMD instruction-based parallel processing is implemented. Utilizing the AVX2 instruction set, multiple 32-bit words can be processed simultaneously, further improving throughput.

[0076] This embodiment designs a dynamic compilation and scheduling system as a key component of the core algorithm layer (Numba JIT acceleration) of the National Cryptography Algorithm Platform. By coordinating with the overall platform architecture, it achieves dynamic performance optimization of the National Cryptography Algorithm. The system first uses a hot 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 backtracing technology to collect performance indicators such as function call frequency, execution time, and memory access patterns, and stores the data in the performance event buffer. Then, the threshold filtering algorithm is expressed as

[0077] in and Represents the execution time and number of calls of function f respectively. This expression is used to judge the effect of these two indicators on the overall time of the program. and the total number of calls Whether the proportion of and , to determine whether function f is a computationally intensive hotspot. Automatically identify and mark frequently called computationally intensive functions such as the SM2 dot product operation (kG_fast) and the SM3 compression function (CF) as optimization candidates.

[0078] Next, the compilation strategy loading mechanism constructs a feature vector based on the target hardware architecture characteristics by querying the instruction set extensions supported by the CPU through the cpuid instruction or / proc / cpuinfo

[0079]

[0080] Each item in this 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 compilation parameter set S is selected to generate highly optimized machine code for each algorithm module in the core algorithm layer. At the same time, the loop unrolling factor, instruction scheduling strategy and memory alignment parameters are adjusted according to the processor microarchitecture characteristics.

[0081] Finally, the cache management mechanism maintains a persistent cache pool of JIT compilation results. By function signature hash

[0082] As the index key, where {code}(f) represents the source code or bytecode of function f, The SHA-256 hash function is used to combine the two parameters. The generated machine code is stored in a shared memory area or disk file (.jitcache), supporting cross-process sharing of compiled machine code and implementing a "compile once, execute many times" optimization strategy. The LRU algorithm also periodically cleans up infrequently used compilation results. The coordinated operation of these three mechanisms enables the core algorithm layer's national secret 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 strong underlying performance support for the API interface layer to receive highly concurrent cryptographic service requests without changing its standardized interface or the calling logic of the business service layer.

[0083] This embodiment implements full lifecycle management of keys through the data model layer and the business service layer. The management system implements full-process security control of keys through four key links: key generation, secure storage, distribution and rotation, and audit and destruction.

[0084] 1. Key generation: This is implemented in the "Key Service" of the business service layer. High-entropy keys are quickly generated using the Numba-accelerated quantum random number generator (QRNG) in the core algorithm layer. This generator uses a quantum noise sampling algorithm optimized with the @njit(fastmath=True) decorator. Generate high-quality random numbers, where represents the 256-bit random state of the previous iteration, is the raw random sample collected in real time from the hardware entropy source, α is an irrational constant (golden ratio) used to enhance the mixing effect, and ⊕ and · represent bitwise XOR and multiplication respectively. This expression generates a new random state by mixing the historical state with the new physical entropy source data and constraining it to a 256-bit moduli space. At the same time, the entropy estimator defined by NIST SP 800-90B Real-time monitoring of randomness to ensure that the entropy value is not less than 0.997 bits / bit; this calculation is done by The probability of occurrence Instead of performing a weighted sum (Σ) of the logarithm with base 2, the original entropy is adjusted using the SM3 hash function to eliminate potential statistical biases. Finally, the generated random bytes are directly mapped to the key material through zero-copy memory management, ensuring the efficiency and security of key generation.

[0085] 2. Secure storage: This is mainly 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. The underlying database table structure is mapped by defining the KeyModel data model (`id`, `key_name`, `key_type`, `key_value`, `iv`, `created_at`, `expires_at`, `status`). The database model relationship between user (User) and key (Key) is as follows Figure 3 As shown. Using the national encryption SM4-CBC mode Implement transparent encryption; Represents the i-th ciphertext block generated by the current calculation. Is the core SM4 symmetric encryption function, which uses the key K to encrypt the input data. The input part of the expression, is the i-th plaintext data block to be encrypted, ⊕ is the bitwise XOR operator, and is the previously generated ciphertext block, Is a random initialization vector. The key value is first passed through the PBKDF2 key derivation function before being stored in the database The processed master key is encrypted, and atomic operations are ensured through database transactions (Session.commit()) to ensure the security of the key during storage.

[0086] 3. Distribution and rotation: Coordinated by the "Key Service" of the business service layer and utilizing the SM2 encryption module of the core algorithm layer. The pre-compiled SM2 encryption module is used to achieve secure key transmission, and the session key $k$ is encrypted with the recipient's public key $P_B$ to generate the ciphertext ,in , , , ; The first part C represents the final output ciphertext formed by the concatenation of three parts (||). is an elliptic curve point, obtained by scalar multiplication of a temporary random number k with the public base point G of the curve ( ) is obtained, the purpose of which is to enable the receiver to calculate the shared secret. Part II It is the encrypted core data, which is a bitwise XOR (⊕) operation between the original plaintext M and a key stream generated by the key derivation function KDF The input used by the KDF here is , is the sender using the temporary random number k and the receiver's public key Perform another scalar multiplication The coordinates of the shared secret point are obtained. Part III It is a message authentication code that performs SM3 hash operation on the coordinates of the shared secret point and the original plaintext M. Generate a key for the recipient to verify data integrity after decryption. An automated rotation strategy (trigger:time:0 0 1 * *, usage_count:1000, action:generate_newkey, transition:active_archive, new→active) is used to regularly update keys. Key versioning (incrementing the key_version field) ensures smooth transitions and prevents security risks associated with long-term key use. These features are exposed through the "Key Management" route ( / api / keys) at the API layer.

[0087] 4. Audit and destruction: Mainly managed and executed by the "key service" of the business service layer, and recorded through the data model layer. The integrated blockchain log system records the key operation track and records the key operation events.

[0088] Through SM3 hash chain Storage ensures that the log cannot be tampered with, while also enabling distributed consensus verification and ensuring the traceability of key usage. In the audit and traceability system for the entire key lifecycle, the expression E = {timestamp, operation, key_id, operator, result}* defines a structured key operation event record. Here, E is a data set that serves as the atomic unit written to the hash chain. Its internal parameters are defined as follows: timestamp is a high-precision timestamp that precisely records the moment the operation occurred; operation is an enumeration field that describes the operation type, such as key generation, distribution, or destruction; key_id is the unique identifier of the key affected by the operation, used to associate it with the specific key entity; operator records the identity of the user or system process performing the operation to ensure accountability; and result indicates the final 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, the secure erase instruction set (write0xFF, write0x00, writerandom() × 3) implements physical destruction of the key. Direct access to memory pages (mlock / munlock) locks sensitive data to prevent swapping to disk. An explicit memory clear function (memset_s) is called immediately after the operation to eliminate the risk of key leakage. These audit and destruction operations will also be exposed to external management interfaces through the API interface layer.

[0089] The API interface layer (FastAPI) in this embodiment is located between the front-end application layer and the business service layer, and is the core portal for the platform to provide external services. 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. For specific interface definitions, please refer to Figure 2 The diagram of the API interface document is shown.

[0090] 1. Algorithm service encapsulation: This module directly corresponds to Figure 1The "SM2 Router," "SM3 Router," "SM4 Router," and "ZUC Router" in the core API interface layer were designed. Standardized endpoints, such as / api / sm2 / sign, / api / sm3 / hash, and / api / sm4 / encrypt, were designed to comply with the GM / T 0009 specification. Each endpoint rigorously validates input parameters using a request model to ensure data formats comply with national encryption standards. Furthermore, a dependency injection system was used for interface authentication, and encryption requests were handled via asynchronous handlers. The underlying algorithm implementation (i.e., the SM2, SM3, SM4, and ZUC modules in the core algorithm layer) was decoupled from the HTTP interface, achieving a highly cohesive and low-coupling service architecture.

[0091] 2. Key management interface: This module corresponds to Figure 1 The "Key Management" route ( / api / keys) in the API interface layer is designed. A complete key lifecycle management API, such as / api / keys / generate, / api / keys / rotate, and / api / keys / revoke, is designed. Permission management is implemented through fine-grained role-based access control (RBAC), defining an enumeration of key operation permissions and integrating middleware to implement interface-level permission control. Furthermore, database transactions ensure the atomicity of key operations and support the secure generation, storage, rotation, and revocation of keys. These interfaces work closely with the "Key Service" (key_service.py) in the business service layer and the "Key Models" (key_models.py) in the data model layer to provide full key lifecycle management capabilities.

[0092] 3. Performance monitoring: Although this module Figure 1 Although not directly listed as a standalone module, its functionality is embedded within the API interface layer, providing monitoring support both upstream (front-end application layer) and downstream (business service layer, core algorithm layer). A Prometheus metrics exposer is built in, and monitoring code is injected through middleware. Key performance indicators such as algorithm latency, data throughput, and cache hit rate are defined, and operational data is collected in real time, exposing monitoring metrics through dedicated endpoints. Furthermore, a custom logging middleware is implemented to record request details, providing data support for performance optimization and problem diagnosis.

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

[0094] The front-end application layer in this embodiment is the only interface for the national encryption algorithm platform to interact with users. Figure 1 The front-end application layer (Vue 3 + Vite) is clearly identified in the platform and sits at the top of the platform, communicating with back-end services through the API interface layer. This layer builds a modern front-end system based on Vue 3 and Element Plus, delivering a complete user experience across three dimensions: interface design, functionality, and technical architecture.

[0095] 1. Technology Stack Selection: In 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 achieves fast hot reload and efficient packaging, significantly improving development efficiency. The introduction of Pinia state management instead of Vuex enables cross-component data sharing and optimizes the state management mechanism. The use of Vue Router to implement routing control based on the history API ensures the modernization and efficiency of the system architecture, which directly corresponds to Figure 1 The "Routing Management (Vue Router)" and "State Management (Pinia)" modules of the mid- and front-end application layers.

[0096] 2. Core page implementation: This section is the specific embodiment of the "view components (SM2 / SM3 / SM4 / ZUC)" in the front-end application layer. The login / registration page implements data validation through the form component and integrates the OAuth 2.0 protocol to support single sign-on, providing users with a secure authentication entry. The key management page uses table components and paging controls to display and paginate keys, and combines dialog components to implement the key operation interface. This works closely with the "key management" routing of the API interface layer and the "key service" of the business service layer to provide users with intuitive key lifecycle management functions. The algorithm operation page has designed independent card-style layouts for SM2, SM3, SM4, and ZUC. Each card contains an input area, an operation area, and a result display area, and integrates data loading animations and operation feedback prompts to ensure that users have a friendly interactive experience when using the various national secret algorithm services provided by the API interface layer.

[0097] 3. Technical architecture optimization: In the front-end application layer, theme switching and dark mode support are implemented through the CSS variable system, which improves the customizability of the user interface. Combining Flex layout and Grid layout ensures responsive adaptation, so that the platform can provide good display effects on different devices. At the same time, the introduction of transition animation and keyframe animation optimizes page switching and component interaction, enhancing the smoothness of the user experience. Multi-language support is achieved through internationalization plug-ins, expanding the user range of the platform. Role-based permission control is implemented based on the RBAC model, sidebar menus are dynamically generated, and illegal access is blocked, ensuring the security of the system and user experience. This works in conjunction with the "authentication routing" of the API interface layer and the "user service" of the business service layer to provide comprehensive permission management functions.

[0098] This invention uses the common national cryptographic algorithm on the market for speed comparison testing. Through comprehensive performance comparison testing of this project's national cryptographic algorithm with mainstream libraries gmssl and pysmx, it is verified that this project's national cryptographic algorithm has a significant optimization effect in multi-dimensional algorithm scenarios. In the SM2 asymmetric algorithm test, this project's national cryptographic algorithm compresses the time taken for 50 random number multiplications from 250.59 ms of gmssl to 5.81 ms by pre-calculating the base point and the fast multiplication algorithm (Montgomery ladder method). The specific performance comparison is as follows: Figure 4 As shown in the figure, the signature and verification process uses a hybrid coordinate system and sliding window optimization. After acceleration, the signature takes 0.29 ms, which is only 4.1% of gmssl, and the end-to-end key agreement takes 5.2ms, which is 6 times faster than the traditional ECDH protocol (30.82ms). For a detailed performance comparison, see Figure 5 and Figure 6 As shown, it meets the high concurrency requirements of most scenarios. Functional testing further verified the integrity and compatibility of the project's national encryption algorithm: SM2 encryption and decryption successfully restored the standard test vector (the decryption result was completely consistent with the SM2 specification), the shared key generated by key negotiation matched the national encryption example, and the R value of the digital signature met the expectations of SM2_A.2.

[0099] In the SM3 hash algorithm test, the national secret algorithm of this project compressed the hashing time of a long message (1488.4B) from 900.11ms of gmssl to 1.17ms through memory block parallel computing and dynamic preprocessing technology. The accelerated version (mysm3) even reached 0.33% of the traditional library pysmx, and the secondary hashing time was only 9.3μs, which was 98% lower than the first hashing time, demonstrating the advantages of JIT compilation and cache reuse. The performance comparison of the first hash and the continuous hashing is as follows: Figure 7 and Figure 8As shown, this fully demonstrates the advantages of JIT compilation and cache reuse. Performance analysis data shows that SM3's CF function accounts for 97% of the computation time, providing a clear direction for subsequent optimization.

[0100] In the SM4 encryption and decryption test, the national secret algorithm of this project optimizes the S-box calculation process through Numba real-time compilation, and combines the pre-calculated round key technology to increase the round function execution efficiency by 12 times. In ECB mode, the self-developed acceleration library (mysm4) takes only 2.65ms to encrypt a long message (1463.9B), which is 0.72% of gmssl; in CBC mode, the self-developed library accelerates the inter-block XOR operation through vectorized instructions (AVX2), and the long message decryption takes 3.43ms, which is 99.4% lower than pysmx, and the initialization time (54.0μs) is only 8.5% of gmssl, which is suitable for high-frequency key switching scenarios. Regardless of the long message (such as Figure 9 ) or a short message (as shown Figure 10 As shown in the figure, the performance of the self-developed acceleration library (mysm4) is better than the comparison library.

[0101] In the ZUC stream cipher test, the national secret algorithm of this project uses the SIMD instruction set to optimize the key stream generation logic, compressing the total encryption time of 50 long messages (average 1528.4B) from 628.42ms of pysmx-ZUC to 4.63ms, and the single initialization time (8.5μs) is reduced by 96% compared with the traditional library. The performance comparison results are shown below. Figure 11 As shown, it is suitable for low-latency communication of IoT devices.

[0102] The present invention proposes a national secret algorithm acceleration platform based on Numba just-in-time compilation technology. By deeply integrating cryptographic mathematical models with 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 the national secret algorithm. For computationally intensive operations such as elliptic curve point multiplication, hash iterative round function, and block encryption transformation, the algorithm execution efficiency is significantly improved through numerical calculation model reconstruction and instruction-level optimization, while maintaining the maintainability and cross-platform compatibility of the code. In the SM2 asymmetric algorithm, the computational overhead of elliptic curve scalar multiplication is greatly reduced by pre-calculating the base point and the fast point multiplication algorithm, which significantly improves the efficiency of signing and verification, and optimizes the key negotiation process, making it perform well in high-concurrency scenarios. Functional testing further verifies the integrity and compatibility of the algorithm to ensure that it complies with national secret standards. In the SM3 hash algorithm, the computational efficiency of long message hashing is significantly improved through memory block parallel computing and dynamic preprocessing technology. At the same time, the performance of secondary hashing is further optimized through JIT compilation and cache reuse technology, reflecting the efficiency and stability of the algorithm. In the SM4 encryption and decryption algorithm, the S-box calculation process is optimized through Numba real-time compilation, combined with the pre-calculated round key technology, the efficiency of block encryption is significantly improved, especially in ECB and CBC modes, showing excellent encryption and decryption performance, suitable for high-frequency key switching scenarios. In the ZUC stream cipher algorithm, the SIMD instruction set is used to optimize the key stream generation logic, significantly improving the encryption efficiency of the stream cipher. At the same time, through low-latency initialization design, it is suitable for real-time communication needs of IoT devices. In addition, the present invention reduces dependence on specific hardware platforms through transfer learning and hardware adaptation optimization, and enhances the versatility and scalability of the algorithm. Experimental results show that the present invention exhibits excellent stability and robustness under different data scales and computing scenarios, especially in long message processing and high concurrency scenarios.

[0103] The present invention is described with reference to flowcharts and / or block diagrams of methods, devices (systems), and computer program products according to embodiments of the present invention. It should be understood that each process and / or block in the flowcharts and / or block diagrams, as well as combinations of processes and / or blocks in the flowcharts 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, a special-purpose computer, an embedded processor, or other programmable data processing device to produce a machine, so that the instructions executed by the processor of the computer or other programmable data processing device generate instructions for implementing the processes in the flowcharts and / or block diagrams. Figure 1 a process or multiple processes and / or boxes Figure 1 A device that provides the functions specified in a block or multiple blocks.

[0104] These computer program instructions may also be stored in a computer readable memory that can direct a computer or other programmable data processing device to work in a specific manner, so that the instructions stored in the computer readable memory produce an article of manufacture comprising an instruction device, which implements the process Figure 1 a process or multiple processes and / or boxes Figure 1 The function specified in one or more boxes.

[0105] These computer program instructions can also be loaded onto a computer or other programmable data processing device so that a series of operational steps are executed on the computer or other programmable device to produce a computer-implemented process, thereby providing the instructions executed on the computer or other programmable device for implementing the process. Figure 1 a process or multiple processes and / or boxes Figure 1 A step that specifies a function in one or more boxes.

[0106] Specific embodiments are used in the present invention to illustrate the principles and implementation methods of the present invention. The description of the above embodiments is only used to help understand the method of the present invention and its core ideas. At the same time, for those skilled in the art, according to the ideas of the present invention, there may be changes in the specific implementation methods and application scopes. In summary, the contents of this specification should not be understood as limiting the present invention.

[0107] Those skilled in the art will appreciate that the embodiments described herein are intended to help readers understand the principles of the present invention, and it should be understood that the scope of protection of the present invention is not limited to such specific descriptions and embodiments. Those skilled in the art can make various other specific variations and combinations based on the technical teachings disclosed in the present invention without departing from the essence of the present invention, and such variations and combinations are still within the scope of protection of the present invention.

Claims

1. A national secret algorithm acceleration system based on Numba just-in-time compilation technology, characterized by: include: The core algorithm layer is used to use Numba's LLVM compilation chain to reconstruct the numerical calculation model of the SM2 elliptic curve scalar multiplication, SM3 message expansion round function, SM4 nonlinear transformation and ZUC flow generation logic included in the core calculation module of the national secret algorithm, convert the interpreted Python code into hardware-adapted optimized machine code; and realize key function compilation acceleration through the @njit decorator, dynamically identify hot operations through compilation scheduling and load differentiated instruction optimization strategies; The data model layer is used to map the underlying database table structure through the key model; The business service layer is used to implement key generation, secure storage, distribution rotation, and audit destruction through key services; The API interface layer is used to build a RESTful API service layer based on the FastAPI framework to implement service encapsulation, key management interface and performance monitoring; The front-end application layer is used to build the front-end system based on Vue 3 and Element Plus, and realize user interaction through interface design, function implementation and technical architecture.

2. The national secret algorithm acceleration system based on Numba just-in-time compilation technology according to claim 1 is characterized in that: The core algorithm layer reconstructs the numerical calculation mode of SM2 elliptic curve scalar multiplication, including: Pre-calculate and store parameters through the pre_kG function The query matrix, It is a fixed point pre-defined 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; The C extension library _ec_lib is used to implement the Montgomery modular multiplication algorithm, converting the operands to the Montgomery domain for calculation and then converting them back to the normal domain. Perform inverse element pre-calculation when the SM2 class is initialized, calculate And solve ,in, It is the remainder operation; Using result cache for signature functions ; The final generated digital signature pair The second key component in; is the signer's private key, is a secret integer; It is a temporary random number; is the first component of the signature pair, It's a temporary one coordinates; and n is the base point of the elliptic curve of order; Use the Jacobi coordinate system to transform the affine coordinate points Mapped to three-dimensional Jacobian coordinates , , ; Implement point addition and point doubling operations in the ec_ws_add and ec_ws_double functions; Use ctypes to load and define function prototypes, and load precalculated data when the ECC_Curve class is initialized.

3. The national secret algorithm acceleration system based on Numba just-in-time compilation technology according to claim 1 is characterized in that: The core algorithm layer reconstructs the numerical calculation mode of the SM3 message extension round function, including: Use np.frombuffer to create an array directly from a byte stream, apply the @njit decorator to statically compile the compression function CF (Compression Function) and the auxiliary function i8_u4, and convert Python dynamic type code into LLVM (Low Level Virtual Machine) intermediate representation; The Boolean function operations involved convert branch judgments into bitwise operation expressions; Numpy's uint32 type array is used to ensure that state variables are stored continuously in memory, providing support for branchless vectorization (SIMD) parallel computing enabled by the JIT (Just-in-Time) compiler; and round constants are preloaded, while bitwise operations such as circular left shift are directly compiled into efficient CPU native instructions.

4. The national secret algorithm acceleration system based on Numba just-in-time compilation technology according to claim 1 is characterized in that: The core algorithm layer reconstructs the numerical calculation model of SM4 nonlinear transformation, including: Expand the 8-bit S-box into a 16-bit pre-computed lookup table by pre-computing and storing the replacement results corresponding to all possible 16-bit input values; Implement block-level parallel encryption in Electronic Codebook (ECB) mode using the @njit(parallel=True) decorator and the prange parallel iterator. Multithreaded parallel processing of independent data blocks during encryption is combined with a cache-friendly chunking strategy to optimize throughput for large data volumes. Through loop unrolling and register reuse compilation optimization technology, the core linear transformation function is compiled into a branchless vectorized (SIMD) instruction sequence; Adopt in-place state update technology to reduce memory copy overhead, and securely pre-allocate round key buffers through thread-local storage to support high-concurrency encryption and decryption; The core computational logic within the round function is restructured to combine the independent nonlinear byte replacement and linear diffusion transformation into a single composite algebraic operation, aiming to reduce function call overhead and the number of accesses to intermediate results. Precompute and cache all system parameters and round constants required for the encryption process.

5. The national secret algorithm acceleration system based on Numba just-in-time compilation technology according to claim 1 is characterized in that: The core algorithm layer reconstructs the numerical calculation mode of the ZUC flow generation logic, including: Refactor the conditional shift operations in core state updates into branchless arithmetic shifts combined with masks, and merge the modular reduction operations with consecutive bitwise operations to eliminate branch prediction overhead; The linear transformation and nonlinear S-box table lookup in bit reorganization are separated into independent pipeline stages. A pure arithmetic logic unit (ALU) instruction sequence is generated through multi-stage shift XOR logic. Pre-computation and constant folding techniques are used to optimize the table lookup operation into an efficient register load. Through 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 register operations. At the same time, zero-copy technology is combined to create data views to avoid memory copying; By using loop unrolling and software pipelining techniques, four consecutive rounds of state updates and key generation operations are overlapped. The extended mode of ZUC-256 uses the Advanced Vector Extensions (AVX2) instruction set to process multiple 32-bit words simultaneously, realizing parallel processing based on SIMD instructions.

6. The national secret algorithm acceleration system based on Numba just-in-time compilation technology according to claim 1 is characterized in that: The core algorithm layer dynamically identifies hotspot operations through compilation and scheduling and loads differentiated instruction optimization strategies including: Through the hot function identification mechanism, the runtime performance of the algorithm core module is analyzed. Sampling and call stack analysis are used to collect key performance indicators of function call frequency and execution time. By filtering the performance data based on preset thresholds, the most computationally intensive function modules are automatically identified and marked. A dynamic compilation policy loading mechanism is used. This mechanism first identifies the instruction set architecture supported by the processor through hardware feature detection. It then uses a decision model to select the optimal compilation optimization parameter set for the identified hotspot functions, ultimately generating machine code adapted to the current hardware. It then fine-tunes instruction scheduling and memory access strategies based on the specific microarchitecture. A cache management mechanism for compilation results is adopted, which maintains a persistent cache pool to store the compiled machine code and uses the hash value based on the function signature as a 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 national secret algorithm acceleration system based on Numba just-in-time compilation technology according to claim 1 is characterized in that: The data model layer maps the underlying database table structure through the key model, including: Multi-level encrypted key storage is implemented based on the SQLAlchemy ORM layer, mapping the underlying database table structure by defining the KeyModel data model. During the persistence process, the system uses a national secret block cipher algorithm to encrypt key data, and this encryption process is transparent to upper-layer applications. Moreover, the key used to encrypt the key itself is securely derived from the user master key through a password-based key derivation function. The atomicity of the entire storage process is guaranteed by the database's transaction mechanism.

8. The national secret algorithm acceleration system based on Numba just-in-time compilation technology according to claim 1 is characterized in that: The business service layer uses key services to implement key generation, secure storage, distribution rotation, and audit destruction, including: Using just-in-time (JIT) compilation technology to accelerate a hardware-based true random number generator (TRNG) for rapid high-entropy key generation. This process samples and post-processes raw physical noise for randomness, and performs real-time entropy evaluation according to the NIST SP 800-90B standard to ensure that the final random number output meets cryptographic security requirements. The secure distribution and packaging of key materials are achieved through the national secret asymmetric encryption protocol. Keys are regularly rotated using an automated lifecycle management strategy based on time and frequency of use, ensuring a smooth transition of services through a version control mechanism. By building an unalterable audit log based on a cryptographic hash chain, the entire life cycle of the key is tracked and recorded. During the key destruction phase, strict security destruction procedures are followed, including using professional instructions to overwrite the storage area and forcibly clearing memory residues to prevent key information from being recovered.

9. The national secret algorithm acceleration system based on Numba just-in-time compilation technology according to claim 1 is characterized in that: The API interface layer builds a RESTful API service layer based on the FastAPI framework, implementing service encapsulation, key management interfaces, and performance monitoring, including: Standardized endpoints are used, each of which strictly verifies input parameters through the request model. A dependency injection system is used to implement interface authentication. Encrypted requests are processed through asynchronous processors, and the underlying algorithm implementation is decoupled from the HTTP interface, achieving a highly cohesive and low-coupling service architecture. The key lifecycle management API is used to implement permission management through fine-grained role-based access control. It defines key operation permission enumeration and implements interface-level permission control in combination with middleware. At the same time, the atomicity of key operations is ensured through database transactions, supporting the secure generation, storage, rotation, and revocation of keys. It has built-in performance monitoring capabilities and provides monitoring support to the front-end application layer, business service layer, and core algorithm layer. It also has a built-in Prometheus indicator exposer that injects monitoring code through middleware, defines key performance indicators, collects operating data in real time, and exposes monitoring indicators through dedicated endpoints. It also has a custom log middleware that records request details.

10. The national secret algorithm acceleration system based on Numba just-in-time compilation technology according to claim 1 is characterized in that: The front-end application layer builds a front-end system based on Vue 3 and Element Plus, and implements user interaction through interface design, function implementation and technical architecture, including: Using Vue 3 as the core framework, combined with the Composition API to achieve logic reuse and component-based development; using the Vite build tool to achieve fast hot reload and efficient packaging; introducing Pinia state management instead of Vuex to achieve cross-component data sharing and optimize the state management mechanism; using Vue Router to implement routing control based on the history API; On the key management page, table components and paging controls are used to display and paginate keys, 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. Each card contains an input area, an operation area, and a result display area, and integrates data loading animations and operation feedback prompts. Theme switching and dark mode support are achieved through the CSS variable system, and responsive adaptation is ensured by combining Flex layout and Grid layout. At the same time, transition animation and keyframe animation are introduced to optimize page switching and component interaction, and multi-language support is achieved through internationalization plug-ins. Role permission control is implemented based on the RBAC model, sidebar menus are dynamically generated, and illegal access is blocked.

Citation Information

Patent Citations

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

    CN117075905A

  • Python Serverless function cold start optimization system and method

    CN119201284A

  • Simulation program tuning acceleration method and system

    CN120336144A

  • SM4 hardware acceleration and anti-side channel protection method and system for domestic FPGA

    CN120358028A

  • Method for accelerating the computational speed of a computer algorithm

    WO2007009002A2