A unified encryption and decryption service method and device based on an event-driven architecture, equipment and medium
By adopting a unified encryption and decryption service method based on an event-driven architecture, the problems of scattered key management and untimely configuration synchronization are solved, achieving zero-downtime hot reloading and cluster consistency, improving the security and availability of encryption and decryption services, and reducing operation and maintenance costs.
Patent Information
- Application Number
- CN202611143431.2
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-07-30
- Publication Date
- 2026-11-03
AI Technical Summary
Existing encryption and decryption schemes suffer from fragmented key management, high security risks, and the need to restart services for configuration changes, which affects business continuity. In cluster environments, untimely configuration synchronization poses a risk to data consistency. Furthermore, there is a lack of unified security auditing and access control, and the repeated implementation of encryption and decryption logic leads to high maintenance costs.
A unified encryption/decryption service approach based on an event-driven architecture is adopted. Through configuration listening, hot reloading, and distributed synchronization mechanisms, it achieves zero-downtime hot reloading of encryption configurations and real-time configuration synchronization between cluster nodes. A client version identification mechanism and a security protection chain are introduced to achieve high availability and consistency of the encryption/decryption service.
It achieves zero downtime for encryption and decryption services during configuration updates, real-time configuration synchronization between cluster nodes, reduces the risk of key leakage, supports canary releases and rapid rollbacks of configurations, reduces operation and maintenance costs, and improves security and scalability.
Smart Images

Figure CN123035103A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of data security technology, and in particular to a unified encryption and decryption service method, apparatus, device, and medium based on an event-driven architecture. Background Technology
[0002] In internet software systems, sensitive data (such as user information, passwords, business parameters, payment vouchers, etc.) requires encryption and decryption protection during transmission and storage to prevent data leakage and unauthorized tampering. As businesses expand, they typically have multiple product lines (such as management systems, official websites, cloud platforms, mobile applications, etc.), each containing multiple subsystems (such as order systems, payment systems, user systems, etc.). Furthermore, each subsystem requires different encryption keys and algorithm strategies in different environments such as development, testing, pre-release, and production to meet security and compliance requirements.
[0003] Currently, existing encryption and decryption schemes typically employ the following methods: Each product line implements its own encryption and decryption logic, hard-coding encryption keys in code or configuration files. There is a lack of unified encryption and decryption service interfaces and standardized calling conventions between different subsystems. Some enterprises use simple encryption utility classes or software development kits (SDKs) for various systems to use, but key generation, storage, distribution, and rotation remain scattered across different systems, lacking a centralized, unified management mechanism. When a new product line needs to be added, encryption algorithms changed, or keys updated, operations and maintenance personnel need to modify the configuration of each system and restart the service one by one, a cumbersome and error-prone process.
[0004] Furthermore, in multi-node cluster deployment scenarios, when an administrator updates the encryption configuration on one node (such as switching encryption algorithms or changing keys), other nodes cannot detect the configuration change in real time. This can lead to different nodes using different versions of keys or algorithms to encrypt and decrypt the same data within the same time period, resulting in data corruption or decryption failure. Although some existing technologies attempt to achieve configuration synchronization by periodically pulling from the configuration center, the polling interval is difficult to set reasonably: too short an interval will increase the access pressure on the configuration center, while too long an interval will lead to excessively high configuration synchronization delays, and the risk of data inconsistency still exists.
[0005] Disadvantages of existing technology: (i) Decentralized key management poses high security risks The encryption keys for each product line are stored separately in their respective code repositories or configuration files, lacking centralized management. The keys are stored in plaintext or weakly encrypted form, posing a high risk of leakage. During key rotation, operations personnel need to manually update each system individually, a complex and error-prone process that results in some systems still using leaked old keys, creating security vulnerabilities.
[0006] (ii) Configuration changes require a service restart, which affects business continuity. When adding new product lines, subsystems, changing encryption algorithms, or updating keys, existing solutions typically require operations personnel to modify configuration files and restart the entire service process. During the restart, the encryption / decryption service is unavailable, preventing users from performing encryption / decryption operations. For critical business systems such as those in finance and e-commerce that require 24 / 7 uninterrupted operation, restarting the service directly impacts business continuity, causing transaction interruptions or data backlogs. While some solutions support hot configuration reloading, this is limited to simple parameter updates and cannot enable dynamic replacement or version switching of encryption implementations.
[0007] (iii) Untimely configuration synchronization in a cluster environment poses a risk to data consistency. In multi-node cluster deployment scenarios, existing technologies typically use timed fetching or restart loading to achieve configuration synchronization. When an administrator updates the encrypted configuration on one node, other nodes cannot detect the change in real time, resulting in the following problems: Firstly, during the configuration of synchronization delay, different nodes use inconsistent keys or algorithms, resulting in different ciphertexts obtained by encrypting the same data on different nodes, or failure to decrypt due to key mismatch, leading to abnormal data interaction between systems. Secondly, the configuration versions between nodes are inconsistent, making it difficult for operations and maintenance personnel to trace and confirm the currently effective configuration version of each node. This makes troubleshooting difficult and time-consuming after a problem occurs. Third, the lack of a versioned configuration management mechanism makes it impossible to support canary releases and rapid rollbacks of configurations. If a new configuration has a problem, it cannot be quickly restored to the previous stable version.
[0008] (iv) The encryption and decryption logic is repeatedly implemented, resulting in high maintenance costs. Each product line independently develops its encryption / decryption module, resulting in a large amount of duplicated code. Due to differing understandings among developers regarding parameter settings, padding modes, and encoding methods for the same algorithm, compatibility issues may arise between different subsystems, leading to "same algorithm, different implementations" problems and preventing cross-system data decryption. Furthermore, when encryption algorithms need upgrades or security vulnerability fixes, all product lines must be simultaneously modified, resulting in high coordination costs, long lead times, and delayed security vulnerability fixes.
[0009] (v) Lack of unified security auditing and access control Existing solutions typically lack authentication and fine-grained access control for callers of encryption / decryption services. Any system that knows the interface address can call the encryption / decryption interface, making product-level access control impossible. Furthermore, encryption / decryption operation logs are scattered across various systems, making unified logging and auditing impossible. This hinders the detection of abnormal encryption / decryption behavior (such as high-frequency decryption attempts or unauthorized product calls), and makes it difficult to pinpoint the source of security incidents. Summary of the Invention
[0010] The technical problem to be solved by the present invention is to provide a unified encryption and decryption service method, apparatus, device and medium based on event-driven architecture, which realizes zero-downtime hot loading of encryption configuration and real-time configuration synchronization between cluster nodes, thereby improving the availability and consistency of encryption and decryption services.
[0011] In a first aspect, the present invention provides a unified encryption and decryption service method based on an event-driven architecture, comprising the following steps: Step S1: Listen for modification events of the target configuration file of the encryption / decryption service. When the target configuration file is modified, trigger the configuration update process. Step S2: Parse the modified target configuration file to generate new version configuration information, and based on the new version configuration information, without restarting the encryption / decryption service, dynamically load the new version encryption implementation class into the mapping table of the registry, and switch the currently effective configuration version in the registry from the old version to the new version according to the new version configuration information; Step S3: In response to the triggering of the configuration update process, the node in the cluster that completed step S2 acts as a producer, generates a configuration update message based on the new version configuration information. The configuration update message includes at least the product identifier and the version number of the new version configuration information, and broadcasts the configuration update message to other nodes in the cluster through a distributed publish-subscribe mechanism, so that the other nodes can perform local configuration cache synchronization operations based on the configuration update message. Step S4: Receive an encryption / decryption request. Based on the client version identifier carried in the encryption / decryption request, route from the registrar to the target encryption implementation class that matches the client version identifier to perform the encryption / decryption operation.
[0012] Secondly, the present invention provides a unified encryption / decryption service apparatus based on an event-driven architecture, comprising: Configure a listening module to monitor modification events of the target configuration file for the encryption / decryption service. When the target configuration file is modified, trigger the configuration update process. The hot-load update module parses the modified target configuration file to generate new version configuration information, and based on the new version configuration information, dynamically loads the new version of the encryption implementation class into the mapping table of the registry without restarting the encryption and decryption service, and switches the currently effective configuration version in the registry from the old version to the new version according to the new version configuration information. In response to the configuration update process, the distributed synchronization module, in response to the triggering of the configuration update process, the node in the cluster that completes the hot reload update module acts as a producer, generates a configuration update message based on the new version configuration information, the configuration update message includes at least a product identifier and the version number of the new version configuration information, and broadcasts the configuration update message to other nodes in the cluster through a distributed publish-subscribe mechanism, so that the other nodes can perform local configuration cache synchronization operations based on the configuration update message; The request processing module receives encryption / decryption requests and, based on the client version identifier carried in the encryption / decryption request, routes the request from the registrar to the target encryption implementation class that matches the client version identifier to perform encryption / decryption operations.
[0013] Thirdly, the present invention provides an electronic device including a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor executes the program to implement the method described in the first aspect.
[0014] Fourthly, the present invention provides a computer-readable storage medium having a computer program stored thereon, which, when executed by a processor, implements the method described in the first aspect.
[0015] One or more technical solutions provided by this invention have at least the following technical effects or advantages: 1. This invention introduces a file-listening-based event-driven mechanism and a registry pattern. When the target configuration file is modified, the system automatically triggers a configuration update process. Without restarting the encryption / decryption service, the new version of the encryption implementation class is dynamically loaded into the registry's mapping table, and the currently effective configuration version is switched from the old version to the new version through atomic operations. Compared with existing technologies where configuration changes require a service restart to take effect, this invention achieves millisecond-level hot configuration updates. The encryption / decryption service remains available throughout the configuration update process, and the caller's encryption / decryption requests are not interrupted, thus ensuring the continuous 24 / 7 operation of critical business systems such as finance and e-commerce. Actual testing shows that under 1000 TPS of concurrent requests, the average time for hot-loading and switching configurations is only 120ms, with a 100% request success rate.
[0016] 2. This invention introduces a versioned cache synchronization scheme based on a distributed publish-subscribe mechanism. The node that completes the configuration update in the cluster acts as the producer, publishing the configuration update message, including the product identifier and version number, to a preset channel of the distributed cache. Other nodes, acting as consumers, subscribe to this channel to receive the configuration update message in real time and immediately invalidate the corresponding key and configuration entry in their local memory cache. When a subsequent request arrives, the latest configuration is retrieved from the distributed cache and updated to local memory. Compared with existing technologies that use timed retrieval or restart loading, this invention achieves near real-time synchronization of configurations between cluster nodes, with P99 synchronization latency controlled within 380ms. This eliminates the "encryption / decryption gap" problem caused by inconsistent configurations, ensuring that the same data can be correctly encrypted and decrypted on different nodes, avoiding the risk of data corruption or decryption failure.
[0017] 3. This invention introduces a client version identification mechanism. The encryption / decryption request carries the client's desired configuration version number, and the registrar routes the request to the matching target encryption implementation class based on this version number. Once the new configuration takes effect, upgraded clients use the new version for encryption and decryption, while clients that haven't upgraded can still use the old version normally. The old and new versions coexist without interference. Furthermore, the configuration file's modification history records complete configuration information for each version. If a problem arises with the new configuration, the administrator only needs to restore the configuration file to the previous version and save it; the system will automatically trigger a rollback process. Compared to existing solutions where all systems are immediately affected after a configuration switch, this invention supports canary releases and rapid rollbacks of configurations, significantly reducing the trial-and-error costs and security risks associated with configuration changes.
[0018] 4. This invention manages encryption algorithms and key configurations for various product lines, subsystems, and environments centrally within a YAML configuration file by constructing a unified encryption / decryption API service and a configuration-driven registrar mechanism. When adding a new product line or subsystem, only the encryption class needs to be implemented and configuration items added; no modification to any core routing or scheduling logic is required, achieving a highly efficient "configuration-as-access" expansion model. Compared to existing technologies where each product line independently implements encryption / decryption logic and keys are stored in a distributed manner, this invention significantly reduces the operational costs and manpower required for multi-product encryption / decryption management.
[0019] 5. This invention employs a master key to provide secondary encryption protection for the business key. The business key is stored in ciphertext form in environment variables or configuration files, and is dynamically decrypted and restored at runtime. Even if the configuration file or environment variables are leaked, attackers only obtain the ciphertext business key; without the master key, they cannot recover the plaintext key, significantly reducing the risk of key leakage. Furthermore, each product and environment uses independent business keys, achieving isolated key management; a single key leak does not affect the data security of other product lines or environments.
[0020] 6. This invention adopts a registry pattern and a configuration-driven architecture, completely decoupling the core scheduling logic from the specific encryption implementation. When adding a new encryption algorithm, only the encryption base class needs to be inherited, the standard interface implemented, and registration completed; no modification to the scheduling layer code is required. When modifying the encryption strategy, only the YAML configuration file needs to be adjusted; no changes to the business logic code are necessary. This highly decoupled design gives the system excellent scalability and maintainability, enabling rapid response to business changes and security compliance requirements.
[0021] 7. This invention constructs a three-layer security protection chain consisting of a request log middleware, a frequency limiting middleware, and a fine-grained API Key access control middleware. This achieves authentication of the caller of the encryption / decryption service, product-level permission control, request frequency limiting, and end-to-end operation auditing. When any protection layer detects abnormal behavior, the system terminates the request processing flow and returns a corresponding rejection response, effectively preventing unauthorized access, interface abuse, and malicious attacks, and ensuring the secure and stable operation of the encryption / decryption service.
[0022] The above description is merely an overview of the technical solution of the present invention. In order to better understand the technical means of the present invention and to implement it in accordance with the contents of the specification, and in order to make the above and other objects, features and advantages of the present invention more apparent and understandable, specific embodiments of the present invention are described below. Attached Figure Description
[0023] The present invention will be further described below with reference to the accompanying drawings and embodiments.
[0024] Figure 1 This is a flowchart of the method in Embodiment 1 of the present invention; Figure 2 This is a schematic diagram of the device in Embodiment 2 of the present invention. Detailed Implementation
[0025] The overall concept of the technical solution in this application is as follows: Build a unified encryption and decryption service platform based on an event-driven architecture. Through a four-step closed-loop mechanism of "listening to trigger → hot reloading and switching → distributed synchronization → version-compatible routing", it can achieve zero-downtime dynamic updates of encryption configurations and ensure cluster consistency in multi-product, multi-environment, and multi-node scenarios.
[0026] Specifically, the present invention constructs a technical solution from the following four levels: (a) Automatic detection and triggering of configuration changes This invention abandons the traditional approach of manually modifying configurations and restarting services, as is common in existing technologies. Instead, it integrates a dedicated configuration monitoring thread within the encryption / decryption service, utilizing the operating system's underlying file system event monitoring interface to monitor modification events of the target configuration file in real time. Once the configuration file changes, the system automatically triggers a configuration update process without manual intervention. Furthermore, this invention calculates the hash value of the configuration file as a version number and compares it with the version number of the currently effective configuration. The update process is only triggered when the configuration content has actually changed, avoiding system overhead caused by invalid updates.
[0027] (ii) Zero-downtime hot loading of a single node This invention introduces a hot-loading scheme based on the registry pattern and a custom class loading mechanism. When a configuration change is triggered, the system dynamically replaces the encryption implementation class without restarting the encryption / decryption service process, through the following methods: First, the system parses the modified configuration file and generates a new version configuration object containing complete information such as product identifier, subsystem tag, encryption method name, key length, and key conversion method. Secondly, the system dynamically loads the bytecode of the new version of the encryption implementation class (such as AES-CBC encryption class, SM4 encryption class, etc.) into memory through a custom class loader, and associates and maps it with the corresponding product identifier and subsystem tag; Finally, the system temporarily stores the new version configuration information in a temporary storage area and performs an integrity check. After the check passes, it uses an atomic operation to point the configuration mapping pointer in the registrar to the new version configuration, while marking the old version as expired.
[0028] The atomic switching mechanism described above ensures that the configuration mapping in the registry is always in a consistent state at any time during configuration updates, and there will be no half-update state with mixed old and new configurations, thus avoiding encryption and decryption errors caused by data inconsistency during the configuration update process.
[0029] (iii) Distributed configuration synchronization of cluster nodes This invention recognizes that hot reloading on a single node only solves the configuration update problem for a single service. In multi-node cluster deployment scenarios, the real-time synchronization of configuration changes across nodes must be addressed. Therefore, this invention introduces a versioned caching synchronization scheme based on a distributed publish-subscribe mechanism.
[0030] The node that completes the configuration update in the cluster acts as the message producer, publishing the configuration update message, containing key information such as the product identifier and new version number, to a pre-defined channel in a distributed cache (such as Redis). Other nodes in the cluster act as message consumers, subscribing to this channel to receive configuration update messages in real time. Upon receiving a message, each node immediately invalidates the corresponding old configuration entry in its local memory cache. When subsequent encryption / decryption requests arrive, the node pulls the latest configuration from the distributed cache and updates it to its local memory, completing the entire synchronization loop.
[0031] The aforementioned "proactive failure + on-demand backfilling" synchronization mechanism ensures the eventual consistency of configurations across all nodes in the cluster while avoiding the performance overhead caused by frequent queries to the distributed cache, thus achieving a balance between high performance and high consistency.
[0032] (iv) Compatible Routers for New and Old Versions This invention further recognizes that during the transition period of configuration updates, due to the small time window of distributed synchronization, different nodes may briefly be in different configuration version states. Furthermore, the calling system may also experience version upgrade discrepancies. Simply routing all requests to the new configuration version will cause decryption failures for callers that have not yet upgraded or nodes that have not yet completed synchronization.
[0033] To address this, this invention introduces a client version identifier field into the encryption / decryption request. During request processing, the registrar compares the version number carried in the request header with the version number of the currently effective configuration: if they match, the new version encryption implementation class is invoked; if they do not match, the old version encryption implementation class corresponding to the client version identifier is invoked, or a source lookup process is triggered to obtain the correct configuration. This compatible routing mechanism ensures that the new and old versions can run in parallel without interfering with each other during the transition period, truly achieving seamless switching. Example 1
[0034] like Figure 1 As shown, this embodiment provides a unified encryption / decryption service method based on an event-driven architecture, including the following steps: Step S1: Listen for modification events of the target configuration file of the encryption / decryption service. When the target configuration file is modified, trigger the configuration update process. Step S2: Parse the modified target configuration file to generate new version configuration information, and based on the new version configuration information, without restarting the encryption / decryption service, dynamically load the new version encryption implementation class into the mapping table of the registry, and switch the currently effective configuration version in the registry from the old version to the new version according to the new version configuration information; Step S3: In response to the triggering of the configuration update process, the node in the cluster that completed step S2 acts as a producer, generates a configuration update message based on the new version configuration information. The configuration update message includes at least the product identifier and the version number of the new version configuration information, and broadcasts the configuration update message to other nodes in the cluster through a distributed publish-subscribe mechanism, so that the other nodes can perform local configuration cache synchronization operations based on the configuration update message. Step S4: Receive an encryption / decryption request. Based on the client version identifier carried in the encryption / decryption request, route from the registrar to the target encryption implementation class that matches the client version identifier to perform the encryption / decryption operation.
[0035] In this embodiment, preferably, in step S1, a separate background thread uses the file system's event listening interface to listen for modification events of the target configuration file, and calculates the hash value of the modified target configuration file as the version number of the new version configuration information.
[0036] In this embodiment, preferably, step S2, which involves dynamically loading the new version of the encryption implementation class into the registry's mapping table, specifically includes: The bytecode of the new version of the encryption implementation class is loaded from a specified path using a custom class loader, and the new version of the encryption implementation class is associated and mapped with the product identifier and subsystem tag contained in the new version configuration information. In step S2, switching the currently effective configuration version in the registration tool from the old version to the new version based on the new version configuration information specifically includes: The parsed new version configuration information is stored in a temporary storage area, and the integrity of the new version configuration information is verified. After the integrity verification is passed, the configuration mapping pointer in the registrar is pointed to the new version configuration information in the temporary storage area through an atomic operation, and the old version configuration information is marked as expired.
[0037] In this embodiment, preferably, in step S3, the other nodes perform a local configuration cache synchronization operation according to the configuration update message, specifically including: Other nodes in the cluster act as consumers, receiving the configuration update message by subscribing to a preset channel of the distributed cache, and invalidating the corresponding key and configuration entry in the local memory cache according to the product identifier and version number carried in the configuration update message; When the other nodes receive an encryption / decryption request carrying the version number of the new version configuration information, and determine that there is no corresponding valid configuration in the local memory cache, they pull the new version configuration information from the distributed cache and update it to the local memory cache.
[0038] In this embodiment, preferably, step S4, which involves routing from the registrar to the target encryption implementation class matching the client version identifier carried in the encryption / decryption request, specifically includes: Extract the version field from the request header of the encryption / decryption request as the client version identifier; Determine whether the client version identifier matches the version number of the currently effective configuration version in the registration tool; If they match, the new version of the encryption implementation class will be called for processing. If there is a discrepancy, the old version of the encryption implementation class corresponding to the client version identifier will be called for processing, or the process of checking the source will be triggered to obtain the correct configuration.
[0039] In this embodiment, preferably, an authentication step is included before step S4: Extract the API Key from the HTTP header of the encryption / decryption request, and authenticate the API Key based on the pre-built API Key hash cache; If authentication fails, the encryption / decryption request processing flow is terminated, and an authentication failure response is returned to the caller. If authentication is successful, the list of allowed products associated with the API Key is retrieved from the API Key hash cache, and the target product identifier carried in the encryption / decryption request is verified to be in the list of allowed products. If the verification fails, the encryption / decryption request processing flow is terminated, and an insufficient permission response is returned to the caller. If the verification passes, the configuration information of the API Key is cached in the current request context, and subsequent processing steps are executed.
[0040] In this embodiment, preferably, a current limiting step is included before step S4: The request frequency is counted using the token bucket algorithm based on the source IP address of the encryption / decryption request. When the number of requests to the source IP address exceeds a preset threshold within a preset time window, a rejection response indicating that the frequency has exceeded the limit is returned to the caller.
[0041] In this embodiment, preferably, before triggering the configuration update process when the target configuration file is modified, step S1 further includes: Calculate the hash value of the modified target configuration file and use the hash value as the version number of the new version configuration information; Determine whether the version number is consistent with the version number of the currently effective configuration version in the registration tool; If they match, the configuration update process is terminated; if they do not match, the configuration update process continues.
[0042] Based on the same inventive concept, this application also provides an apparatus corresponding to the method in Embodiment 1, as detailed in Embodiment 2. Example 2
[0043] like Figure 2 As shown, this embodiment provides a unified encryption / decryption service device based on an event-driven architecture, including: Configure a listening module to monitor modification events of the target configuration file for the encryption / decryption service. When the target configuration file is modified, trigger the configuration update process. The hot-load update module parses the modified target configuration file to generate new version configuration information, and based on the new version configuration information, dynamically loads the new version of the encryption implementation class into the mapping table of the registry without restarting the encryption and decryption service, and switches the currently effective configuration version in the registry from the old version to the new version according to the new version configuration information. In response to the triggering of the configuration update process, the distributed synchronization module, the node in the cluster that completes the hot reload update module acts as a producer, generates a configuration update message based on the new version configuration information, the configuration update message includes at least a product identifier and the version number of the new version configuration information, and broadcasts the configuration update message to other nodes in the cluster through a distributed publish-subscribe mechanism, so that the other nodes can perform local configuration cache synchronization operations based on the configuration update message; The request processing module receives encryption / decryption requests and, based on the client version identifier carried in the encryption / decryption request, routes the request from the registrar to the target encryption implementation class that matches the client version identifier to perform encryption / decryption operations.
[0044] In this embodiment, preferably, the configuration listening module uses an independent background thread to listen for modification events of the target configuration file through the file system's event listening interface, and calculates the hash value of the modified target configuration file as the version number of the new version configuration information.
[0045] In this embodiment, preferably, the step of dynamically loading the new version of the encryption implementation class into the registry's mapping table in the hot-loading update module specifically includes: The bytecode of the new version of the encryption implementation class is loaded from a specified path using a custom class loader, and the new version of the encryption implementation class is associated and mapped with the product identifier and subsystem tag contained in the new version configuration information. In the hot-load update module, the step of switching the currently effective configuration version in the registration tool from the old version to the new version based on the new version configuration information specifically includes: The parsed new version configuration information is stored in a temporary storage area, and the integrity of the new version configuration information is verified. After the integrity verification is passed, the configuration mapping pointer in the registrar is pointed to the new version configuration information in the temporary storage area through an atomic operation, and the old version configuration information is marked as expired.
[0046] In this embodiment, preferably, in the distributed synchronization module, the other nodes perform a local configuration cache synchronization operation according to the configuration update message, specifically including: Other nodes in the cluster act as consumers, receiving the configuration update message by subscribing to a preset channel of the distributed cache, and invalidating the corresponding key and configuration entry in the local memory cache according to the product identifier and version number carried in the configuration update message; When the other nodes receive an encryption / decryption request carrying the version number of the new version configuration information, and determine that there is no corresponding valid configuration in the local memory cache, they pull the new version configuration information from the distributed cache and update it to the local memory cache.
[0047] In this embodiment, preferably, the step of routing from the registrar to the target encryption implementation class matching the client version identifier based on the client version identifier carried in the encryption / decryption request in the request process module specifically includes: Extract the version field from the request header of the encryption / decryption request as the client version identifier; Determine whether the client version identifier matches the version number of the currently effective configuration version in the registration tool; If they match, the new version of the encryption implementation class will be called for processing. If there is a discrepancy, the old version of the encryption implementation class corresponding to the client version identifier will be called for processing, or the process of checking the source will be triggered to obtain the correct configuration.
[0048] In this embodiment, preferably, an authentication module is included before the request processing module: Extract the API Key from the HTTP header of the encryption / decryption request, and authenticate the API Key based on the pre-built API Key hash cache; If authentication fails, the encryption / decryption request processing flow is terminated, and an authentication failure response is returned to the caller. If authentication is successful, the list of allowed products associated with the API Key is retrieved from the API Key hash cache, and the target product identifier carried in the encryption / decryption request is verified to be in the list of allowed products. If the verification fails, the encryption / decryption request processing flow is terminated, and an insufficient permission response is returned to the caller. If the verification passes, the configuration information of the API Key is cached in the current request context, and subsequent processing steps are executed.
[0049] In this embodiment, preferably, a rate limiting module is included before the request processing module: The request frequency is counted using the token bucket algorithm based on the source IP address of the encryption / decryption request. When the number of requests to the source IP address exceeds a preset threshold within a preset time window, a rejection response indicating that the frequency has exceeded the limit is returned to the caller.
[0050] In this embodiment, preferably, the configuration monitoring module further includes the following before triggering the configuration update process when the target configuration file is modified: Calculate the hash value of the modified target configuration file and use the hash value as the version number of the new version configuration information; Determine whether the version number is consistent with the version number of the currently effective configuration version in the registration tool; If they match, the configuration update process is terminated; if they do not match, the configuration update process continues.
[0051] Since the apparatus described in Embodiment 2 of the present invention is an apparatus used to implement the method of Embodiment 1 of the present invention, those skilled in the art can understand the specific structure and variations of the apparatus based on the method described in Embodiment 1 of the present invention, and therefore will not be described again here. All apparatuses used in the method of Embodiment 1 of the present invention fall within the scope of protection of the present invention.
[0052] Based on the same inventive concept, this application provides an electronic device embodiment corresponding to Embodiment 1, as detailed in Embodiment 3. Example 3
[0053] This embodiment provides an electronic device, including a memory, a processor, and a computer program stored in the memory and executable on the processor. When the processor executes the computer program, it can implement any of the implementation methods in Embodiment 1.
[0054] Since the electronic device described in this embodiment is the device used to implement the method in Embodiment 1 of this application, those skilled in the art can understand the specific implementation method and various variations of the electronic device in this embodiment based on the method described in Embodiment 1 of this application. Therefore, how the electronic device implements the method in the embodiment of this application will not be described in detail here. Any device used by those skilled in the art to implement the method in the embodiment of this application falls within the scope of protection of this application.
[0055] Based on the same inventive concept, this application provides a storage medium corresponding to Embodiment 1, as detailed in Embodiment 4. Example 4
[0056] This embodiment provides a computer-readable storage medium storing a computer program thereon. When the computer program is executed by a processor, it can implement any of the implementation methods in Embodiment 1. Example 5
[0057] This application provides a unified encryption / decryption service method and system based on an event-driven architecture, applicable to enterprise-level application scenarios with multiple product lines, each containing multiple subsystems, and deployed in a multi-node cluster environment. For ease of understanding, this embodiment uses the encryption / decryption service platform of a large internet company as an example. This company has three product lines: an e-commerce platform, a cloud computing platform, and an enterprise management system. Each product line contains multiple subsystems, and the entire encryption / decryption service platform is deployed in a cluster consisting of three nodes.
[0058] I. System Architecture Overview The unified encryption and decryption service system implemented in this embodiment adopts a layered architecture design, which includes a data layer, a scheduling layer and an access layer from bottom to top.
[0059] The data layer stores and manages various configuration data for the system, primarily including YAML-formatted configuration files, environment variable configuration files, and data in the distributed cache. YAML configuration files define the mapping between subsystem tags and encryption methods for each product, including parameters such as encryption method name, decryption method name, key length, and key conversion method. Environment variable configuration files store the business keys corresponding to each product, subsystem, and environment according to predetermined naming rules. These business keys are encrypted with the master key and stored in ciphertext form to ensure storage security. The distributed cache stores versioned configuration value objects for shared access by all nodes in the cluster.
[0060] The scheduling layer is the core logic layer of the system, mainly comprising a registrar, a configuration listener, a hot-loading engine, and a distributed synchronization engine. The registrar uses a ConcurrentHashMap to maintain the mapping between product identifiers and instances of the cryptographic implementation classes, as well as the currently effective configuration version information. The configuration listener monitors configuration file modification events through the operating system's underlying file event listening interface. The hot-loading engine is responsible for dynamically loading the new cryptographic implementation class when the configuration changes and switching the configuration version through atomic operations. The distributed synchronization engine is responsible for broadcasting configuration update messages among cluster nodes and performing local cache synchronization.
[0061] The access layer handles encryption / decryption requests initiated by external callers and mainly includes authentication middleware, rate limiting middleware, logging middleware, and a routing scheduler. The authentication middleware verifies the caller's API key and checks product-level permissions. The rate limiting middleware controls the request frequency for each client IP based on a token bucket algorithm. The logging middleware records the complete processing chain information for each request. The routing scheduler, based on the product identifier, subsystem tag, and environment parameters in the request, retrieves the corresponding encryption implementation class and method from the registry and performs the actual encryption / decryption operations.
[0062] II. Definition and Initialization of Configuration Files In this embodiment, a YAML-formatted configuration file needs to be predefined before the system starts. This configuration file is the core metadata source driving the entire system's operation, and its structure is as follows.
[0063] The configuration file's top-level section comprises three main parts: product configuration, global settings, and API key configuration. The product configuration section uses a key-value pair structure, with each product as an independent key and its value containing detailed configurations for each subsystem tag under that product. Each subsystem tag's configuration items include the encryption method name, decryption method name, key length (values are 16, 24, or 32, corresponding to AES-128, AES-192, and AES-256 respectively), key conversion method (values are sha256 or direct), and a list of environments supported by that subsystem.
[0064] The following is a specific configuration example. For the order subsystem under the e-commerce platform product, its tag is named "order," the configured encryption method is "aes_cbc_encrypt," the decryption method is "aes_cbc_decrypt," the key length is 32 bytes, and the key conversion method is SHA256. Supported environments include development, testing, pre-release, and production environments. For the user subsystem under the same e-commerce platform product, its tag is named "user," and the configured encryption method is also "aes_cbc_encrypt," but the key length is set to 16 bytes, and the key conversion method is "direct." This granular configuration allows different subsystems within the same product to employ different encryption strategies, meeting diverse security needs.
[0065] The global settings section configures general system parameters, including the connection address for the distributed cache, the default threshold for frequency limits, and log levels. The API key configuration section maintains a list of all legitimate caller API keys, with each API key entry including the key string and a list of products that the key is allowed to access. Upon system startup, this configuration is loaded as a hash dictionary and cached in memory to support authentication queries with O(1) time complexity.
[0066] The environment variable configuration file stores the business keys corresponding to each dimension according to the naming rule {product identifier uppercase}{subsystem label uppercase}{environment uppercase}_KEY. For example, the business key of the product order subsystem of the e-commerce platform in the production environment has an environment variable name of MALL_ORDER_PROD_KEY. The value of this environment variable is not the plaintext business key, but a ciphertext string encrypted with the master key. When the system starts, each node obtains the encrypted business key by reading the environment variable, then decrypts and restores it using the master key, and caches the actual business key in local memory.
[0067] The initialization process executed upon system startup is as follows: First, the system's entry point class reads and parses the YAML configuration file, loading the product configuration and API key configuration into configuration objects in memory. Second, the registrar iterates through each product and its subsystem tag in the product configuration, retrieving method references from the corresponding cryptographic implementation class based on the configured method name using Python's reflection mechanism or Java's introspection mechanism. It then constructs a complete mapping table of product identifiers, subsystem tags, and cryptographic methods, and calculates the hash value of the current configuration as the initial version number, storing it in the registrar. Third, the system iterates through the API key configuration list, constructing a hash dictionary cache using the API key string as the key and the configuration object containing the list of allowed products as the value. Finally, the system starts a configuration listening background thread and a distributed synchronous subscription background thread. The former begins monitoring configuration file change events, while the latter begins subscribing to the distributed cache's configuration update channel, waiting for configuration change events to trigger.
[0068] III. Specific Implementation Methods for Configuring Monitoring and Hot Reloading When operations and maintenance personnel need to add a payment subsystem to an e-commerce platform product, or upgrade the encryption algorithm of an existing order subsystem from AES-CBC to SM4, they only need to edit the YAML configuration file, add or modify the subsystem tag configuration under the corresponding product, and save the file. The system will automatically trigger the configuration update process without the need to manually restart the service.
[0069] The specific implementation of the configuration listener is as follows. At system startup, an independent background daemon thread is created. This thread registers a listener for the target configuration file using the operating system's underlying file event listening interface. For example, in Java, the `WatchService` interface from the Java NIO package can be used to register the directory containing the configuration file, listening for events of type `ENTRY_MODIFY`. In Python, the `Observer` class from the `watchdog` library can be used to monitor the configuration file. When an administrator saves the configuration file, the operating system sends a file modification event to the listening thread, which is then awakened and begins processing the configuration update.
[0070] After being awakened, the listening thread first reads the configuration file content and calculates its hash value as the new version number. Then, it reads the version number of the currently effective configuration from the registry and compares the two. If they match, it means that although the configuration file has been opened and saved, its content has not actually changed. The listening thread terminates the current update process and continues to wait for the next event to avoid system resource consumption caused by invalid updates. If they do not match, it means that the configuration content has indeed changed, and the listening thread starts the hot reload update process.
[0071] The specific implementation of hot reloading updates is as follows. The listening thread first parses the modified configuration file content into a new configuration object, which contains the latest configuration information for all products and all subsystem tags. Based on the product identifier and subsystem tag list in the new configuration object, the listening thread checks each subsystem tag under each product one by one. For newly added subsystem tags, the listening thread loads the corresponding encryption implementation class bytecode from the specified classpath using a custom class loader based on the configured encryption method name, creates an instance of the class, and then writes the mapping relationship between product identifier, subsystem tag, and encryption method instance into a temporary mapping table. For existing subsystem tags, if their configuration has not changed, the existing mapping relationship is reused; if their configuration has changed, the encryption implementation class is reloaded and the mapping relationship is updated in the same way.
[0072] After the temporary mapping table is constructed, the listening thread performs an integrity check on it. This check includes, but is not limited to, the following: checking whether each subsystem tag under each product has a corresponding encryption and decryption method reference and whether the method is indeed callable; checking whether the key length configuration is a valid value among 16, 24, or 32; checking whether the key conversion method configuration is a valid value among sha256 or direct; and checking whether the supported environment list contains at least one environment and whether each environment name conforms to the naming convention. If the integrity check fails, the listening thread discards the temporary mapping table and logs an error. The current configuration update process is terminated, the currently effective configuration remains unchanged, and the system continues to use the old configuration to process requests, ensuring that the service is not affected when the configuration update fails.
[0073] If the integrity check passes, the listening thread atomically switches the registry's configuration mapping pointer from pointing to the old mapping table to pointing to a temporary mapping table. Simultaneously, it updates the currently effective configuration version number to the new version number and marks the old mapping table as expired. Because the pointer switch is an atomic operation, the configuration mapping in the registry remains consistent at any point during the switch, preventing any mixing of old and new configurations. The entire hot-reload process, from saving the configuration file to the completion of the atomic switch, takes approximately 120 milliseconds. During this period, the system's ability to process encryption and decryption requests remains unaffected. Old requests currently being processed continue to use the old configuration, and new requests after the switch is complete immediately use the new configuration, achieving true zero-downtime updates.
[0074] IV. Specific Implementation Methods of Distributed Synchronization In a cluster deployment scenario, the aforementioned hot reloading update only takes effect on the node that triggered the configuration change (hereinafter referred to as the producer node). If other nodes in the cluster (hereinafter referred to as consumer nodes) fail to synchronously detect the configuration change, different nodes will use different versions of the configuration to process requests, which may result in different ciphertexts obtained by encrypting the same data on different nodes, or failure to decrypt due to key mismatch. To address this, this embodiment introduces a versioned cache synchronization scheme based on a distributed publish-subscribe mechanism.
[0075] In this embodiment, the distributed cache uses Redis, leveraging its built-in publish-subscribe functionality to achieve message communication between nodes. Upon system startup, each node, after completing local initialization, starts a background subscription thread. This thread subscribes to a pre-agreed channel using Redis's SUBSCRIBE command; this channel is used to transmit configuration update messages.
[0076] After the producer node completes the aforementioned hot-load update process, i.e., after the atomic switch operation is completed, the producer node's distributed synchronization module immediately constructs a configuration update message. This message is a JSON-formatted string containing at least the following fields: a product identifier field, used to identify the product involved in this change; a subsystem tag field, used to identify the subsystem involved in this change; a new version number field, used to identify the version number of the new configuration; and a timestamp field, used to record the time the configuration change occurred. The producer node's distributed synchronization module publishes this message to a preset channel using Redis's PUBLISH command.
[0077] Upon receiving a message pushed by Redis, the background subscription thread of the consumer node performs a local configuration cache synchronization operation. Specifically, the subscription thread parses the message content, extracting the product identifier, subsystem tag, and new version number. Based on this information, the subscription thread then locates the corresponding configuration entries in its local memory cache (including the business key used by the subsystem, encryption method reference, key length, and key conversion method, etc.), and immediately sets the time-to-live of these entries to zero, forcing them to become invalid. This operation ensures that the consumer node will not continue to use outdated configurations when processing subsequent requests.
[0078] After invalidating the local cache entry, the consumer node enters the on-demand refill phase. When a consumer node subsequently receives an encryption / decryption request, the request header carries the configuration version number expected by the client. Before routing, the request processing thread first checks whether the configuration entry corresponding to the request exists and is valid in the local memory cache. If the local cache is hit and its version number matches the version number in the request, the encryption / decryption operation is performed directly using the configuration in the local cache. If the local cache is not hit, the request processing thread queries the corresponding configuration value object from the distributed cache. This value object contains complete configuration information. After a successful query, the request processing thread writes the configuration value object back to the local memory cache and sets an appropriate time-to-live, then uses the configuration to perform encryption / decryption operations. If the configuration is still not found in the distributed cache, the request processing thread triggers a source lookup process, initiating a synchronous call to the producer node to obtain the correct configuration information.
[0079] The aforementioned "proactive failure plus on-demand backfilling" mechanism ensures eventual consistency of configurations across all nodes in the cluster while avoiding network overhead and performance degradation caused by frequent queries to the distributed cache. Real-world testing shows that in a three-node cluster with a concurrent request pressure of 2000 TPS, the P99 latency for other nodes to complete configuration synchronization is 380 milliseconds, significantly better than the minimum 30-second synchronization latency of existing timed fetch schemes.
[0080] For requests arriving at the consumer node within the synchronization window, the system ensures correct processing through the aforementioned version-compatible routing mechanism, the specific implementation of which will be detailed in the next section.
[0081] V. Specific Implementation Methods for Request Processing and Version Compatibility Routing When an external caller initiates an encryption or decryption request to the encryption / decryption service platform, the request first undergoes processing through multiple layers of middleware in the access layer. Then, the routing scheduler routes the request to the correct encryption implementation class based on the request parameters to perform the actual operation. The following example of a typical encryption request fully illustrates the request processing flow.
[0082] The caller constructs an HTTP POST request. The request body contains the plaintext data to be encrypted, and the request header includes at least the following fields: X-API-Key (for authentication); X-Product (to identify the target product); X-Tag (to identify the target subsystem tag); X-Environment (to identify the current environment); and X-Config-Version (to indicate the configuration version number the caller expects to use). Upon arrival at the system, the request first enters the request logging middleware. This middleware generates a unique request identifier for each request for end-to-end tracing and records the request's method type, Uniform Resource Locator (URL), client IP address, and anonymized API key value, displaying only the first eight characters. After recording the request start time, this middleware passes the request to the next middleware.
[0083] The request then enters the frequency limiting middleware. This middleware implements request frequency control based on the client IP address, employing a memory-stored token bucket algorithm for high-performance rate limiting. Each client IP maintains a token bucket in the system, and the system adds tokens to the bucket at a fixed rate, with each request consuming one token. When the bucket is depleted of tokens, subsequent requests are considered to have exceeded the limit. The middleware checks whether the client IP of the current request has exceeded the limit; if not, it deducts one token from the bucket and allows the request to proceed to the next middleware; if it has exceeded the limit, it immediately terminates the request processing flow, returns an HTTP status code 429 and an error response body containing the error code RATE_LIMIT_EXCEEDED to the caller, and the request will not reach the registry for routing.
[0084] The request enters the authentication middleware. This middleware extracts the value of the X-API-Key field from the HTTP request header and uses this value as the key to perform an O(1) time lookup in a pre-built API key hash dictionary. If the lookup result is empty, it indicates that the API key is invalid or has been deregistered. The middleware immediately terminates the request processing flow and returns an HTTP status code 401 and an error response body containing the error code INVALID_API_KEY to the caller. If the lookup result is not empty, the middleware retrieves the list of allowed products associated with the API key from the hash dictionary and then verifies whether the X-Product field value in the request header is within this list. If it is not within the list, it indicates that the caller does not have permission to access the target product. The middleware immediately terminates the request processing flow and returns an HTTP status code 403 and an error response body containing the error code FORBIDDEN to the caller. If the verification passes, the middleware caches the complete configuration information of the API key in the current request context for subsequent business logic use, and then passes the request to the routing scheduler.
[0085] Upon receiving a request, the routing scheduler retrieves the product identifier, subsystem tag, environment parameters, and client version identifier from the request context, and then executes the routing logic. The first step of the routing logic is to look up the corresponding encryption implementation class instance in the registrar based on the product identifier. The registrar internally maintains a mapping table between product identifiers and encryption implementation class instances. If the product identifier does not exist in the mapping table, the routing scheduler returns an HTTP status code 404 and an error response body containing the error code PRODUCT_NOT_FOUND to the caller. If the product identifier exists, the routing scheduler proceeds to the second step, looking up the corresponding encryption method configuration in the product's configuration based on the subsystem tag. If the subsystem tag does not exist, the routing scheduler returns an HTTP status code 404 and an error response body containing the error code TAG_NOT_FOUND to the caller. If the subsystem tag exists, the routing scheduler proceeds to the third step, retrieving the business key corresponding to the environment from the configuration based on the environment parameters. The key retrieval order is as follows: the custom key carried in the request is used first; if the request does not carry a custom key, the corresponding encryption business key is read from the environment variables according to the naming rules and decrypted using the master key. If key acquisition fails, the routing scheduler returns an HTTP status code 400 and an error response body containing the error code INVALID_KEY to the caller.
[0086] After obtaining the business key, the routing scheduler proceeds to the fourth step: version-compatible routing. The scheduler extracts the client version identifier from the request header and compares it with the version number of the currently effective configuration in the registry. If the client version identifier matches the currently effective version number, it means the caller has noticed the configuration change. The scheduler obtains the new version's encryption method reference from the registry and uses this method and the converted business key to perform the encryption operation. If the client version identifier does not match the currently effective version number, it means the caller has not yet noticed the configuration change or there is a delay in configuration synchronization. The scheduler queries the registry for the old version configuration information corresponding to the client version identifier. If the old version configuration information is still available, it calls the old version's encryption method to perform the encryption operation, ensuring the caller can complete encryption and decryption normally without being affected by the configuration change. If the old version configuration information has been completely cleared or is unavailable, the scheduler triggers a source lookup process, initiating a synchronization call to the producer nodes in the cluster to obtain the correct configuration information corresponding to the client version, and then performs the encryption operation.
[0087] When the encryption method is executed, the business key is first converted. The conversion method is determined by the key conversion method field in the configuration. If the conversion method is SHA256, the system performs a SHA256 hash operation on the UTF-8 encoded byte sequence of the business key string, generating a fixed 32-byte digest value. Then, based on the configured key length, the first 16, 24, or 32 bytes are truncated as the final key for the AES algorithm. If the conversion method is direct, the system directly converts the business key string into a byte sequence according to UTF-8 encoding. If the byte sequence length is greater than or equal to the configured key length, the corresponding number of bytes are truncated; if the byte sequence length is less than the configured key length, zero bytes are padded to the target length. After the conversion is complete, the encryption method uses this key to encrypt the plaintext data in AES-CBC mode, and then base64-encodes the ciphertext before returning it.
[0088] After the encryption / decryption operation is complete, the request processing thread records the processing time and encapsulates the successful result into a JSON response body, returning it to the caller. The response body contains the following fields: a success field (value: true); a data field (containing the encrypted ciphertext data); a product field (containing the product identifier from the response request); a tag field (containing the subsystem tag from the response request); an environment field (containing the environment parameters from the response request); an operation field (indicating the operation type as encrypt); and a timestamp field (recording the timestamp of the request completion). This completes one encryption request processing flow.
[0089] VI. Specific Implementation Methods of Key Protection To ensure the security of business key storage, this embodiment introduces a two-level key protection mechanism based on the master key. The core idea of this mechanism is that the business key is not stored in plaintext in any configuration file or environment variable, but in encrypted form, and is dynamically decrypted and restored at runtime.
[0090] The specific implementation method is as follows. System maintenance personnel first generate a high-strength master key string in a secure environment. This master key is then configured in the operating system environment variables of each cluster node via a secure channel, with the environment variable name being MASTER_KEY. This master key is a system-level key; the encryption and decryption of all business keys depend on this master key. Therefore, the security protection of this master key is the core of system security.
[0091] When a business key needs to be generated for a product, subsystem, or environment, the operations and maintenance personnel first generate a random string that meets security requirements as the plaintext business key, and then call the key encryption tool provided by the system. This tool first reads the MASTER_KEY from the environment variables, generates a 32-byte digest value from the master key string using the SHA256 hash algorithm, and then performs URL-secure Base64 encoding on this digest value to generate a key object conforming to the Fernet symmetric encryption standard format. The tool then uses this Fernet key to symmetrically encrypt the plaintext business key, outputting a Base64 encoded ciphertext string. The operations and maintenance personnel write this ciphertext string into the environment variable configuration file according to the naming rule {product identifier uppercase}{subsystem label uppercase}{environment uppercase}_KEY, and deploy it to each cluster node.
[0092] When the system starts up or when a business key is used for the first time, the key acquisition module reads the corresponding ciphertext string from the environment variables and the MASTER_KEY from the operating system environment variables. It then generates a Fernet key in the same way, decrypts the ciphertext string to obtain the plaintext business key, and caches it in local memory for subsequent encryption and decryption operations. Since the plaintext key in local memory is only valid within the current process's lifecycle, and the business keys of each product are isolated from each other, a leak of a single product's key does not affect the data security of other products. If the master key is leaked, maintenance personnel only need to replace the master key and re-encrypt all business keys to achieve global key rotation.
[0093] VII. Specific Implementation Methods for New Product Integration When a company adds a new product line and needs to integrate with the unified encryption and decryption service, the integration process is extremely simple, requiring no modification to any code in the core framework, and only the following four steps need to be completed.
[0094] The first step is to implement the encryption class. Developers inherit from the system-provided encryption base class, which defines standard encryption and decryption abstract methods. Developers then implement the specific encryption algorithm logic in the subclasses, such as using AES-CBC mode, AES-GCM mode, or the Chinese national standard SM4 algorithm. When implementing this, it's important to note that the encryption method accepts two parameters: a plaintext string and a key string, and returns a Base64-encoded ciphertext string; the decryption method accepts two parameters: a Base64-encoded ciphertext string and a key string, and returns a plaintext string.
[0095] The second step is to add YAML configuration. Developers add a new product-level configuration item to the configuration file, using the new product identifier as the key. Under this key, they add configurations for each subsystem tag according to a predefined format, including the encryption method name, decryption method name, key length, key conversion method, and a list of supported environments. The method names in the configuration must be exactly the same as the method names in the implementation class from the first step.
[0096] The third step is to configure the business key. Developers add the corresponding environment variables in the environment variable configuration file according to the naming rules. The variable value is the encrypted string of the business key, which is encrypted with the master key.
[0097] The fourth step is to configure API key permissions. Developers add the new product identifier to the list of products allowed to be accessed by the corresponding API key in the API key section of the YAML configuration file.
[0098] After completing the above four steps, the developers save the configuration file. The system's configuration monitoring thread detects the configuration file change within seconds and automatically executes a hot reload process, dynamically loading the new product's encryption implementation class into the registry mapping table. The new product is then fully integrated and can immediately provide encryption and decryption services. The entire process requires no service restarts, no modification to core routing logic, and no system redeployment.
[0099] VIII. Specific Implementation Methods of the Error Handling Mechanism This embodiment returns different HTTP status codes and error codes for different types of errors, making it easier for the caller to quickly locate the problem and take appropriate measures.
[0100] When the request lacks an API key or API key authentication fails, the system returns HTTP status code 401 and error code INVALID_API_KEY. When API key authentication is successful but the requested target product is not in the allowed product list for that key, the system returns HTTP status code 403 and error code FORBIDDEN. When the product identifier in the request does not exist in the registrar's mapping table, the system returns HTTP status code 404 and error code PRODUCT_NOT_FOUND. When the subsystem tag in the request does not exist in the product's configuration, the system returns HTTP status code 404 and error code TAG_NOT_FOUND. When the system cannot obtain the corresponding business key based on environment parameters and naming rules, the system returns HTTP status code 400 and error code INVALID_KEY. When the data format in the request does not meet the requirements, such as the ciphertext passed during decryption not being a valid Base64 encoded string, the system returns HTTP status code 400 and error code INVALID_DATA_FORMAT. When an algorithm-related exception occurs during the execution of the encryption method, the system returns HTTP status code 400 and error code ENCRYPTION_FAILED. When a key mismatch or ciphertext corruption-related exception occurs during the execution of the decryption method, the system returns HTTP status code 400 and error code DECRYPTION_FAILED. When the request frequency exceeds a preset threshold, the system returns HTTP status code 429 and error code RATE_LIMIT_EXCEEDED. When an unexpected internal exception occurs, the system returns HTTP status code 500 and error code INTERNAL_ERROR, and simultaneously logs the complete exception stack trace to the log for maintenance personnel to troubleshoot.
[0101] All error responses use a uniform JSON format, including a success field with a value of false, an error_code field, and an error_message field. The error messages do not expose sensitive internal system implementation details to avoid providing attackers with exploitable information.
[0102] Those skilled in the art will understand that embodiments of the present invention can be provided as methods, systems, or computer program products. Therefore, the present invention can take the form of a completely hardware embodiment, a completely software embodiment, or an embodiment combining software and hardware aspects. Furthermore, the present invention can take the form of a computer program product embodied on one or more computer-usable storage media (including, but not limited to, disk storage, CD-ROM, optical storage, etc.) containing computer-usable program code.
[0103] 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.
[0104] 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.
[0105] 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.
[0106] While specific embodiments of the present invention have been described above, those skilled in the art should understand that the specific embodiments described are merely illustrative and not intended to limit the scope of the present invention. Equivalent modifications and variations made by those skilled in the art in accordance with the spirit of the present invention should be covered within the scope of protection of the claims of the present invention.
Claims
1. A unified encryption / decryption service method based on an event-driven architecture, characterized in that, Includes the following steps: Step S1: Listen for modification events of the target configuration file of the encryption / decryption service. When the target configuration file is modified, trigger the configuration update process. Step S2: Parse the modified target configuration file to generate new version configuration information, and based on the new version configuration information, without restarting the encryption / decryption service, dynamically load the new version encryption implementation class into the mapping table of the registry, and switch the currently effective configuration version in the registry from the old version to the new version according to the new version configuration information; Step S3: In response to the triggering of the configuration update process, the node in the cluster that completed step S2 acts as a producer, generates a configuration update message based on the new version configuration information. The configuration update message includes at least the product identifier and the version number of the new version configuration information, and broadcasts the configuration update message to other nodes in the cluster through a distributed publish-subscribe mechanism, so that the other nodes can perform local configuration cache synchronization operations based on the configuration update message. Step S4: Receive an encryption / decryption request. Based on the client version identifier carried in the encryption / decryption request, route from the registrar to the target encryption implementation class that matches the client version identifier to perform the encryption / decryption operation.
2. The method according to claim 1, characterized in that, In step S1, a separate background thread uses the file system's event listening interface to listen for modification events of the target configuration file, and calculates the hash value of the modified target configuration file as the version number of the new version configuration information.
3. The method according to claim 1, characterized in that, In step S2, dynamically loading the new version of the encryption implementation class into the registry's mapping table specifically includes: The bytecode of the new version of the encryption implementation class is loaded from a specified path using a custom class loader, and the new version of the encryption implementation class is associated and mapped with the product identifier and subsystem tag contained in the new version configuration information. In step S2, switching the currently effective configuration version in the registration tool from the old version to the new version based on the new version configuration information specifically includes: The parsed new version configuration information is stored in a temporary storage area, and the integrity of the new version configuration information is verified. After the integrity verification is passed, the configuration mapping pointer in the registrar is pointed to the new version configuration information in the temporary storage area through an atomic operation, and the old version configuration information is marked as expired.
4. The method according to claim 1, characterized in that, In step S3, the other nodes perform a local configuration cache synchronization operation based on the configuration update message, specifically including: Other nodes in the cluster act as consumers, receiving the configuration update message by subscribing to a preset channel of the distributed cache, and invalidating the corresponding key and configuration entry in the local memory cache according to the product identifier and version number carried in the configuration update message; When the other nodes receive an encryption / decryption request carrying the version number of the new version configuration information, and determine that there is no corresponding valid configuration in the local memory cache, they pull the new version configuration information from the distributed cache and update it to the local memory cache.
5. The method according to claim 1, characterized in that, In step S4, the step of routing from the registrar to the target encryption implementation class matching the client version identifier carried in the encryption / decryption request specifically includes: Extract the version field from the request header of the encryption / decryption request as the client version identifier; Determine whether the client version identifier matches the version number of the currently effective configuration version in the registration tool; If they match, the new version of the encryption implementation class will be called for processing. If there is a discrepancy, the old version of the encryption implementation class corresponding to the client version identifier will be called for processing, or the process of checking the source will be triggered to obtain the correct configuration.
6. The method according to claim 1, characterized in that, Before step S4, an authentication step is also included: Extract the API Key from the HTTP header of the encryption / decryption request, and authenticate the API Key based on the pre-built API Key hash cache; If authentication fails, the encryption / decryption request processing flow is terminated, and an authentication failure response is returned to the caller. If authentication is successful, the list of allowed products associated with the API Key is retrieved from the API Key hash cache, and the target product identifier carried in the encryption / decryption request is verified to be in the list of allowed products. If the verification fails, the encryption / decryption request processing flow is terminated, and an insufficient permission response is returned to the caller. If the verification passes, the configuration information of the API Key will be cached in the current request context, and subsequent processing steps will continue. Before step S4, a current limiting step is also included: The request frequency is counted using the token bucket algorithm based on the source IP address of the encryption / decryption request. When the number of requests to the source IP address exceeds a preset threshold within a preset time window, a rejection response indicating that the frequency has exceeded the limit is returned to the caller.
7. The method according to claim 1, characterized in that, In step S1, before triggering the configuration update process when the target configuration file is modified, the following steps are also included: Calculate the hash value of the modified target configuration file and use the hash value as the version number of the new version configuration information; Determine whether the version number is consistent with the version number of the currently effective configuration version in the registration tool; If they match, the configuration update process is terminated; if they do not match, the configuration update process continues.
8. A unified encryption / decryption service device based on an event-driven architecture, characterized in that, include: Configure a listening module to monitor modification events of the target configuration file for the encryption / decryption service. When the target configuration file is modified, trigger the configuration update process. The hot-load update module parses the modified target configuration file to generate new version configuration information, and based on the new version configuration information, dynamically loads the new version of the encryption implementation class into the mapping table of the registry without restarting the encryption and decryption service, and switches the currently effective configuration version in the registry from the old version to the new version according to the new version configuration information. In response to the configuration update process, the distributed synchronization module, in response to the triggering of the configuration update process, the node in the cluster that completes the hot reload update module acts as a producer, generates a configuration update message based on the new version configuration information, the configuration update message includes at least a product identifier and the version number of the new version configuration information, and broadcasts the configuration update message to other nodes in the cluster through a distributed publish-subscribe mechanism, so that the other nodes can perform local configuration cache synchronization operations based on the configuration update message; The request processing module receives encryption / decryption requests and, based on the client version identifier carried in the encryption / decryption request, routes the request from the registrar to the target encryption implementation class that matches the client version identifier to perform encryption / decryption operations.
9. An electronic device comprising a memory, a processor, and a computer program stored in the memory and executable on the processor, characterized in that, When the processor executes the program, it implements the method as described in any one of claims 1 to 7.
10. A computer-readable storage medium having a computer program stored thereon, characterized in that, When the program is executed by the processor, it implements the method as described in any one of claims 1 to 7.
