Iframe two-way encryption communication method and system based on network target range
By using elliptic curve key pairs based on P-384 curves and the ECDH algorithm, combined with AES-GCM encryption, the security and integrity issues in network range communication are solved, and end-to-end secure communication is achieved.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- SAINING WANGAN
- Filing Date
- 2025-07-09
- Publication Date
- 2026-07-14
AI Technical Summary
Existing network range communications suffer from problems such as one-way authentication being vulnerable to attacks, lack of digital signature mechanisms, insufficient information integrity, and easily cracked encryption algorithms, leading to a high risk of sensitive data leakage and tampering.
It employs elliptic curve key pair generation based on P-384 curves, ECDH algorithm key derivation, AES-GCM encryption, and digital signature mechanisms. Through bidirectional exchange of public keys, timestamp verification, and session ID generation between sub-components and parent windows, it ensures the security and integrity of communication.
It achieves forward confidentiality, resistance to replay attacks, and resistance to quantum computing, ensuring data confidentiality, integrity, and identity verification, and preventing communication data from being eavesdropped on or tampered with.
Smart Images

Figure CN120729595B_ABST
Abstract
Description
Technical Field
[0001] This invention belongs to the field of network security technology, specifically relating to a bidirectional encrypted communication method and system for iframes based on network test ranges. Background Technology
[0002] A cyber range is a technology that simulates and reproduces the network architecture, system equipment, business processes, and operating environment in real cyberspace.
[0003] Network range data visualization refers to the use of graphical methods to transform complex data (such as attack traffic, vulnerability exploitation chains, and defense responses) generated during network attack and defense drills and security tests into intuitive visual elements, helping users quickly understand the network confrontation situation and key information. The rendering technology for network range data visualization typically consists of two parts: 2D chart libraries (Echarts, D3.js) and 3D network space rendering technology. The 3D network space rendering technology is usually developed by a third-party platform and ultimately integrated with the front-end via a URL. For network ranges, 3D network space rendering typically displays the three-dimensional network topology and dynamic data generated by attacks and defenses in scenarios such as red team / blue team exercises or specialized competitions. The prerequisite for displaying this data is communication with the front-end page. Therefore, the communication process is encrypted to prevent the leakage of sensitive data and ensure the integrity of the communication.
[0004] Traditional encryption methods typically involve one-way authentication, verifying only the information sent from the front end to the third party. The third party does not filter or identify the information, making it vulnerable to virus attacks or incorrect information acquisition. Traditional encryption lacks digital signature mechanisms, making it impossible to trace the source of messages or prevent sender denial. Currently common encryption methods lack complete information protection, making them susceptible to malicious tampering during communication. Furthermore, some encryption algorithms use fixed keys, allowing for decryption after cracking previous communications, and symmetric encryption may reuse the same key, increasing the risk of leakage. Summary of the Invention
[0005] To address the shortcomings of the existing technologies, this application provides a bidirectional encrypted communication method and system for iframes based on a network test range.
[0006] In its first aspect, this application proposes a bidirectional encrypted communication method for iframes based on a network test range, comprising the following steps;
[0007] Step S1: After the child component is loaded, it generates an elliptic curve key pair based on the P-384 curve, registers a cross-domain message listener by calling window.addEventListener, and sends a child_ready notification to the parent window to establish a preliminary communication link;
[0008] Step S2: In response to the child_ready notification, the parent window sends a handshake_init message containing its own public key in JWK format to the child component. The child component imports the parent window's public key through the crypto.subtle.importKey interface and simultaneously exports its own public key. The two parties exchange public key parameters through the postMessage interface. The exchange process includes a timestamp to prevent replay attacks.
[0009] Step S3: The sub-component uses the ECDH algorithm to derive a key based on the parent window's public key and its own private key, generating a 256-bit AES-GCM session key, and processes the parent window's public key and its own public key using the SHA256 hash algorithm to generate a sessionId that uniquely identifies the current session;
[0010] Step S4: The sub-component digitally signs its own public key coordinates and timestamp information, and returns it to the parent window through the handshake_response message. After the parent window verifies the signature, both parties set the communication connection status connectionStatus to connected, indicating that the encrypted channel has been established.
[0011] Step S5: After the encrypted channel is established, all cross-domain communication data is encrypted and transmitted using the AES-GCM algorithm. During the encryption process, a 12-byte initialization vector and authentication tag are used. The receiver verifies the sessionId to ensure that the received message belongs to the correct communication session.
[0012] In some embodiments, step S1 includes:
[0013] An ECDH key pair based on the P-384 elliptic curve is generated asynchronously via the Web Crypto API. The ECDH key pair consists of a public key and a private key.
[0014] Register a message event listener and handle all messages from the parent window through the this.handleParentMessage callback function to establish the foundation for two-way secure communication;
[0015] Send a ready notification message of type child_ready to the parent window, using the parentOrigin parameter to qualify the message target field.
[0016] In some embodiments, step S2 includes:
[0017] The public key is converted to JWK format using the exportKey method, and a message containing the handshake type identifier, the public key JWK object, and the current timestamp is sent to the target iframe window via the postMessage API. The information transmission process adopts an asynchronous programming mode to ensure that the message is sent only after the key generation and export operations are completed.
[0018] In some embodiments, step S3 includes: when the iframe receives the public key, it performs a deriveKey operation in combination with its own private key, calculates a shared key using the ECDH algorithm, and explicitly specifies the key's purpose as encryption or decryption. The front-end also derives the same session key through a symmetric process, and the front-end and the iframe achieve key consistency without transmitting the key itself.
[0019] In some embodiments, step S5 includes:
[0020] Front-end encrypted sending stage: A session ID is generated using CryptoJS.SHA256, a 12-byte random IV is generated using the Web Crypto API, the message is encoded using TextEncoder and then encrypted using AES-GCM with a pre-shared sessionKey, and finally the ciphertext, IV and session ID are sent to the iframe via postMessage;
[0021] iframe processing stage: Decrypt the message using the same algorithm and sessionKey, verify the consistency of the session ID, process the message and re-encrypt the response;
[0022] Front-end decryption response phase: The data returned by the iframe is decrypted again using AES-GCM. The entire process adopts an end-to-end encryption design, and IVs are dynamically generated for each communication to prevent revisit attacks.
[0023] In some embodiments, step S5 further includes the JSON.stringify method, which is used to serialize the ECDH public key object into a JSON string, and then use CryptoJS.SHA256 to generate a fixed-length unique hash value for the string as a session ID, ensuring that an unpredictable session identifier can be generated each time a key exchange is performed.
[0024] In some embodiments, the AES-GCM provides dual protection through a combination of counter encryption and authentication mechanisms: during encryption, crypto.getRandomValues is used to generate a 12-byte random IV, and a key stream is generated using AES-CTR mode to encrypt the plaintext; at the same time, Galois field multiplication is used to calculate a 128-bit authentication tag on the ciphertext and additional data, and during decryption, the integrity of the tag is verified before decryption.
[0025] Secondly, this application proposes an iframe bidirectional encrypted communication system based on a network test range, including an initialization preparation module, a key exchange module, a session key derivation module, a secure channel establishment module, and an encrypted communication module;
[0026] The initialization preparation module is used to generate an elliptic curve key pair based on the P-384 curve after the sub-component is loaded, register a cross-domain message listener by calling window.addEventListener, and send a child_ready notification to the parent window to establish a preliminary communication link;
[0027] The key exchange module is used by the parent window in response to the child_ready notification to send a handshake_init message containing its own public key in JWK format to the child component. The child component imports the parent window's public key through the crypto.subtle.importKey interface and exports its own public key at the same time. The two parties exchange public key parameters through the postMessage interface. The exchange process includes a timestamp to prevent replay attacks.
[0028] The session key derivation module is used by the sub-component to use the ECDH algorithm to derive a key based on the parent window public key and its own private key, generate a 256-bit AES-GCM session key, and process the parent window public key and its own public key using the SHA256 hash algorithm to generate a sessionId that uniquely identifies the current session.
[0029] The secure channel establishment module is used for the sub-component to digitally sign its own public key coordinates and timestamp information, and return it to the parent window through the handshake_response message. After the parent window verifies the signature, both parties set the communication connection status connectionStatus to connected, indicating that the encrypted channel has been established.
[0030] The encrypted communication module is used to encrypt all cross-domain communication data using the AES-GCM algorithm after the encrypted channel is established. During the encryption process, a 12-byte initialization vector and authentication tag are used. The receiver verifies the sessionId to ensure that the received message belongs to the correct communication session.
[0031] Thirdly, this application proposes an electronic device including a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor, when executing the computer program, implements the steps of the method described above.
[0032] Fourthly, this application provides a computer-readable storage medium storing a computer program that, when executed by a processor, implements the steps of the method described above.
[0033] The beneficial effects of this invention are:
[0034] In terms of data communication between the front-end and the third-party platform iframe, enhanced security was implemented. ECDH key pairs were used to generate digital certificates, laying the foundation for authentication. Subsequently, a TCP handshake was simulated to establish a reliable channel, and two-way authentication against replay attacks was achieved through two-way certificate verification and random number exchange. Next, a shared key was negotiated using ECDH, and a dynamic session key was derived using the HKDF algorithm to ensure forward confidentiality. Finally, AES-GCM was used for real-time data encryption and integrity verification, and a timed key rotation mechanism continuously improved anti-leakage capabilities. The entire process integrates characteristics such as quantum-resistant computing, low resource consumption, and high-efficiency transmission, providing an end-to-end secure communication paradigm for web applications. This prevents cross-session key obfuscation, ensures data confidentiality, integrity, and identity verification during cross-domain communication, and prevents communication data from being eavesdropped on or tampered with. Attached Figure Description
[0035] Figure 1 This is the overall flowchart of the present invention.
[0036] Figure 2 This is a system principle block diagram of the present invention. Detailed Implementation
[0037] Exemplary embodiments of the invention will now be described in more detail with reference to the accompanying drawings. While exemplary embodiments of the invention are shown in the drawings, it should be understood that the invention may be implemented in various forms and should not be limited to the embodiments set forth herein; rather, these embodiments are provided so that a more thorough understanding of the invention can be achieved and that the full scope of the invention can be conveyed to those skilled in the art.
[0038] Firstly, this application proposes a bidirectional encrypted communication method for iframes based on a network test range, such as... Figure 1 As shown, it includes the following steps;
[0039] Step S1: After the child component is loaded, it generates an elliptic curve key pair based on the P-384 curve, registers a cross-domain message listener by calling window.addEventListener, and sends a child_ready notification to the parent window to establish a preliminary communication link;
[0040] In some embodiments, step S1 includes:
[0041] An ECDH key pair based on the P-384 elliptic curve is generated asynchronously via the Web Crypto API. The ECDH key pair consists of a public key and a private key.
[0042] Register a message event listener and handle all messages from the parent window through the this.handleParentMessage callback function to establish the foundation for two-way secure communication;
[0043] Send a ready notification message of type child_ready to the parent window, using the parentOrigin parameter to qualify the message target field.
[0044] Step S2: In response to the child_ready notification, the parent window sends a handshake_init message containing its own public key in JWK format to the child component. The child component imports the parent window's public key through the crypto.subtle.importKey interface and simultaneously exports its own public key. The two parties exchange public key parameters through the postMessage interface. The exchange process includes a timestamp to prevent replay attacks.
[0045] In some embodiments, step S2 includes:
[0046] The public key is converted to JWK format using the exportKey method, and a message containing the handshake type identifier, the public key JWK object, and the current timestamp is sent to the target iframe window via the postMessage API. The information transmission process adopts an asynchronous programming mode to ensure that the message is sent only after the key generation and export operations are completed.
[0047] Step S3: The sub-component uses the ECDH algorithm to derive a key based on the parent window's public key and its own private key, generating a 256-bit AES-GCM session key, and processes the parent window's public key and its own public key using the SHA256 hash algorithm to generate a sessionId that uniquely identifies the current session;
[0048] In some embodiments, step S3 includes: when the iframe receives the public key, it performs a deriveKey operation in combination with its own private key, calculates a shared key using the ECDH algorithm, and explicitly specifies the key's purpose as encryption or decryption. The front-end also derives the same session key through a symmetric process, and the front-end and the iframe achieve key consistency without transmitting the key itself.
[0049] Step S4: The sub-component digitally signs its own public key coordinates and timestamp information, and returns it to the parent window through the handshake_response message. After the parent window verifies the signature, both parties set the communication connection status connectionStatus to connected, indicating that the encrypted channel has been established.
[0050] Step S5: After the encrypted channel is established, all cross-domain communication data is encrypted and transmitted using the AES-GCM algorithm. During the encryption process, a 12-byte initialization vector and authentication tag are used. The receiver verifies the sessionId to ensure that the received message belongs to the correct communication session.
[0051] In some embodiments, step S5 includes:
[0052] Front-end encrypted sending stage: A session ID is generated using CryptoJS.SHA256, a 12-byte random IV is generated using the Web Crypto API, the message is encoded using TextEncoder and then encrypted using AES-GCM with a pre-shared sessionKey, and finally the ciphertext, IV and session ID are sent to the iframe via postMessage;
[0053] iframe processing stage: Decrypt the message using the same algorithm and sessionKey, verify the consistency of the session ID, process the message and re-encrypt the response;
[0054] Front-end decryption response phase: The data returned by the iframe is decrypted again using AES-GCM. The entire process adopts an end-to-end encryption design, and IVs are dynamically generated for each communication to prevent revisit attacks.
[0055] In some embodiments, step S5 further includes the JSON.stringify method, which is used to serialize the ECDH public key object into a JSON string, and then use CryptoJS.SHA256 to generate a fixed-length unique hash value for the string as a session ID, ensuring that an unpredictable session identifier can be generated each time a key exchange is performed.
[0056] In some embodiments, the AES-GCM provides dual protection through a combination of counter encryption and authentication mechanisms: during encryption, crypto.getRandomValues is used to generate a 12-byte random IV, and a key stream is generated using AES-CTR mode to encrypt the plaintext; at the same time, Galois field multiplication is used to calculate a 128-bit authentication tag on the ciphertext and additional data, and during decryption, the integrity of the tag is verified before decryption.
[0057] The specific implementation steps of this solution are as follows:
[0058] 1. Front-end initialization preparation
[0059] mounted() {
[0060] window.addEventListener('message', this.handleChildMessage)
[0061] }
[0062] The front-end prepares an environment for communication with the third-party platform's iframe. It listens for message events to receive information sent by the iframe and specifies the domain name of the trusted child window through childOrigin.
[0063] 2. Trigger a handshake request
[0064] async initHandshake() {
[0065] / / Generate parent ECDH key pair
[0066] this.ecdhKeys = await crypto.subtle.generateKey(...)
[0067] / / Export public key and send it to child iframe
[0068] const publicKey = await crypto.subtle.exportKey('jwk',this.ecdhKeys.publicKey)
[0069] this.$refs.secureIframe.contentWindow.postMessage({
[0070] type: 'handshake_init',
[0071] publicKey,
[0072] timestamp: Date.now()
[0073] })
[0074] }
[0075] First, an Elliptic Curve Diffie-Hellman (ECDH) key pair is generated using the `generateKey` method of the Web Crypto API. This key pair consists of a public key and a private key, using a P-384 curve to provide 192-bit security strength. Then, the public key is converted to JWK (JSON Web Key) format using the `exportKey` method. This structured JSON format facilitates cross-domain key data transmission. Finally, a message containing a handshake type identifier, the public key JWK object, and the current timestamp is sent to the target iframe window via the `postMessage` API. The entire process employs asynchronous programming (async / await) to ensure that message sending only occurs after key generation and export operations are complete. The addition of a timestamp effectively prevents replay attacks, while the use of a ephemeral key pair ensures forward security. This design lays the foundation for establishing an encrypted communication channel and is a crucial first step in building a secure cross-domain communication system.
[0076] 3. iframe communication environment preparation
[0077] async init() {
[0078] / / Generate sub-end ECDH key pair
[0079] ecdhKeys = await crypto.subtle.generateKey(
[0080] { name: 'ECDH', namedCurve: 'P-384'},
[0081] true,
[0082] ['deriveKey'] )
[0084] / / Listen for messages from the parent window
[0085] window.addEventListener('message', this.handleParentMessage)
[0086] / / Send ready notification
[0087] window.parent.postMessage({ type: 'child_ready'},parentOrigin)
[0088] }
[0089] The iframe third-party platform establishes a channel to receive information sent by the front end. It listens for message events to receive information sent by the front end and uses handleParentMessage to process the logic after receiving the information.
[0090] The code above mainly includes three key steps:
[0091] First, an ECDH key pair (containing a public key and a private key) based on the P-384 elliptic curve is generated asynchronously via the Web Crypto API. This key pair will be used for subsequent key derivation operations. The namedCurve: 'P-384' specifies the elliptic curve over a 384-bit prime field to ensure security strength.
[0092] Then register a message event listener and handle all messages from the parent window through the this.handleParentMessage callback function. This is the foundation for achieving two-way secure communication.
[0093] Finally, a ready notification message of type child_ready is actively sent to the parent window, and the parentOrigin parameter is used to strictly limit the target domain of the message to prevent cross-site scripting attacks.
[0094] The entire initialization process adopts a non-blocking asynchronous mode, ensuring that time-consuming operations such as key generation do not affect the main thread of the page. This establishes the necessary cryptographic foundation and environmental preparation for subsequent secure handshakes and encrypted communication. Of particular note is the setting of the deriveKey usage permission during key generation, which provides clear permission control for the subsequent derivation of session keys.
[0095] P-384 is an elliptic curve cryptography curve standardized by NIST, employing a 384-bit prime field and a specific parametric equation y²=x³-3x+b. Its core mechanism involves both parties generating their own public-private key pairs (the private key is a random number, and the public key = private key × base point G). After exchanging public keys, both parties perform a dot product operation using their own private key and the other's public key. Based on the associative law of elliptic curve dot product (d_A×d_B×G = d_B×d_A×G), they generate the same shared key. The x-coordinate of this key is processed by KDF and used as the session key. The entire process relies on the computational difficulty of the elliptic curve discrete logarithm problem to ensure security.
[0096] The ECDH protocol generates a temporary key pair independently for each session (the private key is discarded after use). Leveraging the computational irreversibility of the elliptic curve discrete logarithm problem, it ensures that even if an attacker obtains a long-term private key or intercepts historical communication data, they cannot crack past session keys. Its core protection mechanisms include: ① dynamic key negotiation (generating a new a·b·G shared secret for each session); ② forward security design (temporary private keys are not stored); and ③ key derivation hybridization (HKDF combined with random number hashing). These three mechanisms together provide both mathematical and engineering safeguards, making historical session keys virtually impossible to crack.
[0097] 4. Key Exchange and Derivation
[0098] / / Front-end generates key pair
[0099] this.ecdhKeys = await crypto.subtle.generateKey(
[0100] { name: 'ECDH', namedCurve: 'P-384'},
[0101] true,
[0102] ['deriveKey'] )
[0104] / / Frontend sends handshake request
[0105] const publicKey = await crypto.subtle.exportKey(
[0106] 'jwk',
[0107] this.ecdhKeys.publicKey )
[0109] / / iframe-side derived key (logically symmetric)
[0110] sessionKey = await crypto.subtle.deriveKey(
[0111] { name: 'ECDH', public: parentPublicKey}, / / Frontend public key
[0112] ecdhKeys.privateKey, / / Your own private key
[0113] { name: 'AES-GCM', length: 256}, / / Derived key parameters
[0114] true,
[0115] ['encrypt', 'decrypt'] )
[0117] / / Front-end derived key
[0118] this.sessionKey = await crypto.subtle.deriveKey(
[0119] { name: 'ECDH', public: childPublicKey}, / / Public key on the iframe side
[0120] this.ecdhKeys.privateKey, / / Your own private key
[0121] { name: 'AES-GCM', length: 256}, / / Derived key parameters
[0122] true, / / Key can be exported
[0123] ['encrypt', 'decrypt']
[0124] The end-to-end cryptographic key exchange protocol based on the Web Crypto API adopts the elliptic curve Diffie-Hellman (ECDH) key negotiation mechanism in modern cryptography.
[0125] In the front end, a temporary ECDH key pair is first generated using the P-384 curve (which provides 192-bit security strength), and the public key is converted into JWK format using the exportKey method for transmission.
[0126] After receiving the public key, the iframe performs a deriveKey operation in conjunction with its own private key. It uses the mathematical properties of the ECDH algorithm to calculate the shared key. This process uses AES-GCM-256 as the derived key algorithm (providing 256-bit encryption strength with quantum security level) and explicitly specifies that the key is used for encryption and decryption operations.
[0127] The front-end also derives the same session key through a symmetric process, ultimately achieving key consistency between the two parties without transmitting the key itself. The entire process strictly adheres to the zero-trust principle. Temporary key pairs ensure forward security, the JWK format guarantees standardized key transmission, and the choice of AES-GCM satisfies both confidentiality and integrity requirements. This design is suitable for micro-frontend architectures that require secure cross-domain communication or scenarios with high security requirements. The asynchronous processing (async / await) of each step avoids blocking the UI thread.
[0128] The key exchange and derivation process involves the front-end generating a key pair and sending a handshake request to the iframe. Upon receiving the handshake request, the iframe uses the `deriveKey` method of the Web Crypto API to derive the key and then sends a response to the front-end, informing it that it has received the key and derived the iframe's key. Similarly, after receiving a request from the iframe, the front-end uses the `deriveKey` method of the Web Crypto API to derive its own key. The mathematical principle of the ECDH algorithm is similar: parent private key × child public key = child private key × parent public key = shared key.
[0129] 5. Encrypted communication
[0130] / / ① Encrypting information sent from the front end
[0131] / / Generate Session ID
[0132] this.sessionId = CryptoJS.SHA256(
[0133] JSON.stringify(data.publicKey)
[0134] ).toString()
[0135] / / Send message
[0136] async sendEncryptedMessage(message) {
[0137] const iv = crypto.getRandomValues(new Uint8Array(12))
[0138] const encoded = new TextEncoder().encode(message)
[0139] const ciphertext = await crypto.subtle.encrypt(
[0140] { name: 'AES-GCM', iv},
[0141] this.sessionKey,
[0142] encoded )
[0144] this.$refs.secureIframe.contentWindow.postMessage({
[0145] type: 'encrypted_message',
[0146] payload: Array.from(new Uint8Array(ciphertext)),
[0147] iv: Array.from(iv),
[0148] sessionId: this.sessionId
[0149] )
[0150] }
[0151] / / ②iframe side processes encrypted messages and makes a response
[0152] const sessionId = CryptoJS.SHA256(JSON.stringify(publicKey)).toString();
[0153] const decrypted = await this.decryptMessage(
[0154] new Uint8Array(data.payload),
[0155] new Uint8Array(data.iv) )
[0157] async decryptMessage (payload, iv) {
[0158] const decrypted = await crypto.subtle.decrypt(
[0159] { name: 'AES-GCM', iv},
[0160] sessionKey,
[0161] payload )
[0163] return new TextDecoder().decode(decrypted)
[0164] },
[0165] if (sessionKey) {
[0166] [[ID=2,0]]const reply = await this.encryptMessage('Received message:'+ decrypted)[[ID=2,1]] [[ID=2,2]]
[0167] [[ID=2,3]]event.source.postMessage({[[ID=2,4]] [[ID=2,5]]
[0168] [[ID=2,6]]type: 'encrypted_message',[[ID=2,7]] [[ID=2,8]]
[0169] [[ID=2,9]]...reply,[[ID=3,0]] [[ID=3,1]]
[0170] [[ID=3,2]]sessionId[[ID=3,3]] [[ID=3,4]]
[0171] [[ID=3,5]]}, event.origin)[[ID=3,6]] [[ID=3,7]]
[0172] [[ID=3,8]]}[[ID=3,9]] [[ID=4,0]]
[0173] [[ID=4,1]] / / ③ Front-end receives the response from the iframe[[ID=4,2]] [[ID=4,3]]
[0174] [[ID=4,4]]const decrypted = await this.decryptMessage([[ID=4,5]] [[ID=4,6]]
[0175] [[ID=4,7]]data.payload,[[ID=4,8]] [[ID=4,9]]
[0176] [[ID=5,0]]data.iv[[ID=5,1]] [[ID=5,2]])[[ID=5,3]] [[ID=5,4]]
[0178] [[ID=5,5]]async decryptMessage (payload, iv) {[[ID=5,6]] [[ID=5,7]]
[0179] [[ID=5,8]]const decrypted = await crypto.subtle.decrypt([[ID=5,9]] [[ID=6,0]]
[0180] [[ID=6,1]]{ name: 'AES-GCM', iv: new Uint8Array(iv)},[[ID=6,2]]
[0181] this.sessionKey,
[0182] new Uint8Array(payload) )
[0184] return new TextDecoder().decode(decrypted)
[0185] }
[0186] The secure communication process based on the AES-GCM encryption algorithm is mainly divided into three core stages:
[0187] ① Front-end encrypted sending stage: Generate session ID (based on public key hash value) through CryptoJS.SHA256, generate 12-byte random IV using Web Crypto API, encode the message with TextEncoder, encrypt it with AES-GCM using pre-shared sessionKey, and finally send the ciphertext, IV and session ID to iframe through postMessage;
[0188] ② iframe processing stage: Decrypt the message using the same algorithm and sessionKey, verify the consistency of the session ID, process the message and re-encrypt the response;
[0189] ③ Front-end decryption response phase: The data returned by the iframe is decrypted again using AES-GCM. The entire process employs an end-to-end encryption design, dynamically generating an IV for each communication to prevent replay attacks, using session IDs to ensure communication context consistency, and the AES-GCM algorithm to provide both confidentiality and integrity protection, while the postMessage mechanism enables secure cross-domain communication. This implementation is typically used in web scenarios requiring isolated security contexts.
[0190] The AES-GCM mode achieves dual protection through a combination of counter encryption and authentication mechanisms: during encryption, a 12-byte random IV is generated using `crypto.getRandomValues` (ensuring uniqueness), and the plaintext is encrypted using a keystream generated through AES-CTR mode; simultaneously, a 128-bit authentication tag is calculated using Galois field multiplication on the ciphertext and additional data (generated by XORing the GHASH hash result with the encrypted IV). During decryption, the tag integrity is verified before decryption, achieving an integrated "encryption-authentication" process. This design ensures both data confidentiality and strong integrity verification; the randomness of the IV and the unforgeability of the tag enhance security.
[0191] The further `JSON.stringify(data.publicKey)` serializes the ECDH public key object into a JSON string, and then uses `CryptoJS.SHA256` to generate a fixed-length unique hash value for this string as a session ID, thus ensuring that an unpredictable session identifier is generated for each key exchange. The communication context establishes a secure, source-verified channel between the iframe parent and child windows by strictly verifying the binding between `event.origin` and the preset `parentOrigin`, combined with timestamps and cross-domain `postMessage` mechanisms. Finally, encrypted communication is achieved through a derived AES-GCM session key.
[0192] The following description uses a browser cross-domain secure communication application scenario as an example, combined with the above solution:
[0193] 1. Initialization Preparation Phase
[0194] In this phase, once the subcomponent has loaded, an elliptic curve Diffie-Hellman (ECDH) key pair based on the P-384 curve is immediately generated. The key pair is generated using the browser's window.crypto.subtle.generateKey interface, with a key length of 384 bits, conforming to the NIST standard.
[0195] The child component registers a message listener using `window.addEventListener('message', ...)` to receive messages from the parent window. Subsequently, the child component sends a `child_ready` notification message to the parent window, indicating that it is ready for further communication. At this point, an encrypted channel has not yet been established; only the basic communication environment has been prepared.
[0196] 2. Key Exchange Phase
[0197] Upon receiving the `child_ready` notification, the parent window constructs a `handshake_init` message and sends it to the child component via the `postMessage` interface. This message contains the parent window's ECDH public key, encoded in JWK (JSON WebKey) format.
[0198] Upon receiving the message, the child component uses the `crypto.subtle.importKey` interface to import the parent window's public key as a `SubtleCrypto` object for subsequent key derivation. Simultaneously, the child component exports its own public key in JWK format and sends it to the parent window via `postMessage`.
[0199] During this phase, the public key information exchanged by both parties includes a timestamp field to prevent replay attacks. For example, when a child component sends its own public key, it appends a timestamp, and the parent window checks whether the timestamp is within the allowed window range (e.g., ±5 seconds) during verification.
[0200] 3. Session Key Derivation Phase
[0201] In this phase, the sub-component uses the ECDH algorithm to perform key derivation operations between the parent window's public key and its own private key to generate a shared key. This shared key is generated through the crypto.subtle.deriveKey interface and used as input to generate a 256-bit AES-GCM session key.
[0202] To generate a unique sessionId that identifies the current communication session, the subcomponent concatenates the public keys of both parties (in JWK format) and uses the SHA-256 hash function to calculate its hash value. This sessionId will be used in subsequent communications to identify the current communication context and ensure the correctness of message attribution.
[0203] 4. Safety exit confirmation phase
[0204] In this embodiment, to ensure the authenticity of the identities of both communicating parties, the sub-component digitally signs its own public key's coordinate information (x, y) and timestamp. The signing algorithm uses ECDSA, and the sub-component's private key is used to sign the following data: the signing result is returned to the parent window via a `handshake_response` message. Upon receiving this message, the parent window verifies the signature's validity using the sub-component's public key. If the verification passes, both the parent window and the sub-component set the communication connection status to `connectionStatus` to `true`, indicating that the encrypted channel has been successfully established and both parties can begin encrypted communication.
[0205] 5. Encrypted Communication Phase
[0206] After the encrypted channel is established, all cross-domain communication messages are encrypted and transmitted using the AES-GCM algorithm. The specific steps are as follows:
[0207] The sender generates a 12-byte random initialization vector (IV) and encrypts the plaintext data using the session key.
[0208] During the encryption process, the AES-GCM algorithm generates a 16-byte authentication tag to ensure data integrity.
[0209] The encrypted data structure includes: IV, ciphertext, authentication tag, and the sessionId of the current communication.
[0210] Before decryption, the receiver first checks whether the sessionId matches the current session; if they do not match, the message is discarded.
[0211] The receiver uses the same session key and IV to decrypt the ciphertext and verify the validity of the authentication tag. If authentication fails, the message is deemed to have been tampered with and is rejected.
[0212] Through the above embodiments, this method achieves end-to-end encrypted communication in a browser cross-domain environment. By employing ECDH key exchange, session key derivation, authentication, and AES-GCM encryption mechanisms, it effectively prevents man-in-the-middle attacks, data tampering, and eavesdropping risks, ensuring the security and integrity of the communication process.
[0213] This solution achieves two-way authentication between the front-end and the iframe third-party platform through ECDH key exchange and digital signatures, avoiding the risk of man-in-the-middle attacks. For dynamic key management, it employs a P-384 curve to derive AES-256 keys, generating a temporary session key independently for each session (this strategy uses `crypto.subtle.generateKey` to create ECDHP-384 key pairs; for key independence, each session generates a key pair through an independent handshake process (triggered by the `handshake_init` message). A basic lifespan of 1 hour is set, and the key is rotated immediately when encrypted data exceeds 4GB or a security risk is detected). This provides forward confidentiality. The design optimizes encryption efficiency, using asymmetric encryption for key negotiation (ECDH) and high-performance symmetric encryption (AES-GCM) for actual communication, achieving both encryption and integrity verification. Furthermore, the solution binds the communication context with a unique session ID generated by SHA-256, preventing cross-session key confusion.
[0214] Secondly, this application proposes an iframe bidirectional encrypted communication system based on a network test range, such as... Figure 2 As shown, it includes an initialization preparation module, a key exchange module, a session key derivation module, a secure channel establishment module, and an encrypted communication module;
[0215] The initialization preparation module is used to generate an elliptic curve key pair based on the P-384 curve after the sub-component is loaded, register a cross-domain message listener by calling window.addEventListener, and send a child_ready notification to the parent window to establish a preliminary communication link;
[0216] The key exchange module is used by the parent window in response to the child_ready notification to send a handshake_init message containing its own public key in JWK format to the child component. The child component imports the parent window's public key through the crypto.subtle.importKey interface and exports its own public key at the same time. The two parties exchange public key parameters through the postMessage interface. The exchange process includes a timestamp to prevent replay attacks.
[0217] The session key derivation module is used by the sub-component to use the ECDH algorithm to derive a key based on the parent window public key and its own private key, generate a 256-bit AES-GCM session key, and process the parent window public key and its own public key using the SHA256 hash algorithm to generate a sessionId that uniquely identifies the current session.
[0218] The secure channel establishment module is used for the sub-component to digitally sign its own public key coordinates and timestamp information, and return it to the parent window through the handshake_response message. After the parent window verifies the signature, both parties set the communication connection status connectionStatus to connected, indicating that the encrypted channel has been established.
[0219] The encrypted communication module is used to encrypt all cross-domain communication data using the AES-GCM algorithm after the encrypted channel is established. During the encryption process, a 12-byte initialization vector and authentication tag are used. The receiver verifies the sessionId to ensure that the received message belongs to the correct communication session.
[0220] Thirdly, this application proposes an electronic device including a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor, when executing the computer program, implements the steps of the method described above.
[0221] Fourthly, this application provides a computer-readable storage medium storing a computer program that, when executed by a processor, implements the steps of the method described above.
[0222] Those skilled in the art will clearly understand that, for the sake of convenience and brevity, the above-described division of functional units and modules is merely an example. In practical applications, the above functions can be assigned to different functional units and modules as needed, that is, the internal structure of the device can be divided into different functional units or modules to complete all or part of the functions described above. The functional units and modules in the embodiments can be integrated into one processing unit, or each unit can exist physically separately, or two or more units can be integrated into one unit. The integrated unit can be implemented in hardware or as a software functional unit. Furthermore, the specific names of the functional units and modules are only for easy differentiation and are not intended to limit the scope of protection of this application. The specific working process of the units and modules in the above system can be referred to the corresponding process in the foregoing method embodiments, and will not be repeated here.
[0223] In the above embodiments, the descriptions of each embodiment have different focuses. For parts that are not described in detail or recorded in a certain embodiment, please refer to the relevant descriptions of other embodiments.
[0224] Those skilled in the art will recognize that the units and algorithm steps of the various examples described in conjunction with the embodiments disclosed herein can be implemented in electronic hardware, or a combination of computer software and electronic hardware. Whether these functions are implemented in hardware or software depends on the specific application and design constraints of the technical solution. Those skilled in the art can use different methods to implement the described functions for each specific application, but such implementation should not be considered beyond the scope of this disclosure.
[0225] In the embodiments provided in this disclosure, it should be understood that the disclosed apparatus / computer devices and methods can be implemented in other ways. For example, the apparatus / computer device embodiments described above are merely illustrative. For instance, the division of modules or units is only a logical functional division, and in actual implementation, there may be other division methods. Multiple units or components may be combined or integrated into another system, or some features may be ignored or not executed. Furthermore, the mutual coupling or direct coupling or communication connection shown or discussed may be through some interfaces, and the indirect coupling or communication connection between apparatuses or units may be electrical, mechanical, or other forms.
[0226] The units described as separate components may or may not be physically separate. The components shown as units may or may not be physical units; that is, they may be located in one place or distributed across multiple network units. Some or all of the units can be selected to achieve the purpose of this embodiment according to actual needs.
[0227] Furthermore, the functional units in the various embodiments of this disclosure can be integrated into one processing unit, or each unit can exist physically separately, or two or more units can be integrated into one unit. The integrated unit can be implemented in hardware or as a software functional unit.
[0228] If an integrated module / unit is implemented as a software functional unit and sold or used as an independent product, it can be stored in a computer-readable storage medium. Based on this understanding, all or part of the processes in the methods of the above embodiments can also be implemented by a computer program instructing related hardware. The computer program can be stored in a computer-readable storage medium, and when executed by a processor, it can implement the steps of the various method embodiments described above. The computer program may include computer program code, which can be in the form of source code, object code, executable files, or certain intermediate forms. A computer-readable medium may include: any entity or device capable of carrying computer program code, recording media, USB flash drives, portable hard drives, magnetic disks, optical disks, computer memory, read-only memory (ROM), random access memory (RAM), electrical carrier signals, telecommunication signals, and software distribution media, etc. It should be noted that the content included in a computer-readable medium may be appropriately added to or subtracted according to the requirements of legislation and patent practice in a jurisdiction. For example, in some jurisdictions, according to legislation and patent practice, computer-readable media may not include electrical carrier signals and telecommunication signals.
[0229] The above are merely preferred embodiments of the present invention. It should be noted that any modifications and improvements made by those skilled in the art without departing from the present technical solution should also be considered to fall within the scope of protection claimed by the present solution.
Claims
1. A bidirectional encrypted communication method for iframes based on a network test range, characterized in that: Includes the following steps; Step S1: After the child component is loaded, it generates an elliptic curve key pair based on the P-384 curve, registers a cross-domain message listener by calling window.addEventListener, and sends a child_ready notification to the parent window to establish a preliminary communication link; Step S2: In response to the child_ready notification, the parent window sends a handshake_init message containing its own public key in JWK format to the child component. The child component imports the parent window's public key through the crypto.subtle.importKey interface and simultaneously exports its own public key. The two parties exchange public key parameters through the postMessage interface. The exchange process includes a timestamp to prevent replay attacks. Step S3: The sub-component uses the ECDH algorithm to derive a key based on the parent window's public key and its own private key, generating a 256-bit AES-GCM session key, and processes the parent window's public key and its own public key using the SHA256 hash algorithm to generate a sessionId that uniquely identifies the current session; Step S4: The sub-component digitally signs its own public key coordinates and timestamp information, and returns it to the parent window through the handshake_response message. After the parent window verifies the signature, both parties set the communication connection status connectionStatus to connected, indicating that the encrypted channel has been established. Step S5: After the encrypted channel is established, all cross-domain communication data is encrypted and transmitted using the AES-GCM algorithm. During the encryption process, a 12-byte initialization vector and authentication tag are used. The receiver verifies the sessionId to ensure that the received message belongs to the correct communication session.
2. The method according to claim 1, characterized in that: Step S1 includes: An ECDH key pair based on the P-384 elliptic curve is generated asynchronously via the Web Crypto API. The ECDH key pair consists of a public key and a private key. Register a message event listener and handle all messages from the parent window through the this.handleParentMessage callback function to establish the foundation for two-way secure communication; Send a ready notification message of type child_ready to the parent window, using the parentOrigin parameter to qualify the message target field.
3. The method according to claim 2, characterized in that: Step S2 includes: The public key is converted to JWK format using the exportKey method, and a message containing the handshake type identifier, the public key JWK object, and the current timestamp is sent to the target iframe window via the postMessage API. The information transmission process adopts an asynchronous programming mode to ensure that the message is sent only after the key generation and export operations are completed.
4. The method according to claim 3, characterized in that: Step S3 includes: when the iframe receives the public key, it performs the deriveKey operation in combination with its own private key, calculates the shared key using the ECDH algorithm, and explicitly specifies the key's purpose as encryption or decryption. Meanwhile, the front-end also derives the same session key through a symmetric process, and the front-end and the iframe achieve key consistency without transmitting the key itself.
5. The method according to claim 4, characterized in that: Step S5 includes: Front-end encrypted sending stage: A session ID is generated using CryptoJS.SHA256, a 12-byte random IV is generated using the Web Crypto API, the message is encoded using TextEncoder and then encrypted using AES-GCM with a pre-shared sessionKey, and finally the ciphertext, IV and session ID are sent to the iframe via postMessage; iframe processing stage: Decrypt the message using the same algorithm and sessionKey, verify the consistency of the session ID, process the message and re-encrypt the response; Front-end decryption response phase: The data returned by the iframe is decrypted again using AES-GCM. The entire process adopts an end-to-end encryption design, and IVs are dynamically generated for each communication to prevent revisit attacks.
6. The method according to claim 5, characterized in that: Step S5 also includes the JSON.stringify method, which is used to serialize the ECDH public key object into a JSON string, and then use CryptoJS.SHA256 to generate a fixed-length unique hash value for the string as a session ID, ensuring that an unpredictable session identifier can be generated for each key exchange.
7. The method according to claim 6, characterized in that: The AES-GCM provides dual protection through a combination of counter encryption and authentication mechanisms: during encryption, it uses crypto.getRandomValues to generate a 12-byte random IV and generates a key stream to encrypt the plaintext using AES-CTR mode; at the same time, it uses Galois field multiplication to calculate a 128-bit authentication tag on the ciphertext and additional data, and during decryption, it first verifies the integrity of the tag before decryption.
8. A bidirectional encrypted communication system for iframes based on a network test range, characterized in that: It includes an initialization preparation module, a key exchange module, a session key derivation module, a secure channel establishment module, and an encrypted communication module; The initialization preparation module is used to generate an elliptic curve key pair based on the P-384 curve after the sub-component is loaded, register a cross-domain message listener by calling window.addEventListener, and send a child_ready notification to the parent window to establish a preliminary communication link; The key exchange module is used by the parent window in response to the child_ready notification to send a handshake_init message containing its own public key in JWK format to the child component. The child component imports the parent window's public key through the crypto.subtle.importKey interface and exports its own public key at the same time. The two parties exchange public key parameters through the postMessage interface. The exchange process includes a timestamp to prevent replay attacks. The session key derivation module is used by the sub-component to use the ECDH algorithm to derive a key based on the parent window public key and its own private key, generate a 256-bit AES-GCM session key, and process the parent window public key and its own public key using the SHA256 hash algorithm to generate a sessionId that uniquely identifies the current session. The secure channel establishment module is used for the sub-component to digitally sign its own public key coordinates and timestamp information, and return it to the parent window through the handshake_response message. After the parent window verifies the signature, both parties set the communication connection status connectionStatus to connected, indicating that the encrypted channel has been established. The encrypted communication module is used to encrypt all cross-domain communication data using the AES-GCM algorithm after the encrypted channel is established. During the encryption process, a 12-byte initialization vector and authentication tag are used. The receiver verifies the sessionId to ensure that the received message belongs to the correct communication session.
9. An electronic device comprising a memory, a processor, and a computer program stored in the memory and running on the processor, characterized in that, When the processor executes the computer program, it implements the steps of the method as described in any one of claims 1-7.
10. A computer-readable storage medium, characterized in that: The computer-readable storage medium stores a computer program that, when executed by a processor, implements the steps of the method as described in any one of claims 1-7.