Network range-based iframe bidirectional encryption communication method and system
By using an elliptic curve key pair based on the P-384 curve and the ECDH algorithm, combined with AES-GCM encryption, the security vulnerabilities of traditional encryption methods in the network target range are resolved, and the security and integrity of iframe two-way encrypted communication are achieved, which is suitable for iframe cross-domain communication in the network target range.
Patent Information
- Application Number
- CN202510941688.1
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-07-09
- Publication Date
- 2025-09-30
- Estimated Expiration
- 2045-07-09
AI Technical Summary
Traditional encryption methods in existing network target ranges have problems such as one-way authentication that is vulnerable to attacks, lack of digital signature mechanism, insufficient information integrity and easy cracking of keys, resulting in a high risk of communication data leakage.
Elliptic curve key pair generation based on the P-384 curve, ECDH algorithm key derivation and AES-GCM encryption are used, combined with digital signatures and timestamps to achieve iframe two-way encrypted communication, and key exchange and data transmission are carried out through the Web Crypto API and postMessage interface.
It achieves forward secrecy, resistance to replay attacks and data confidentiality, ensures data confidentiality, integrity and identity verifiability during the communication process, prevents data eavesdropping or tampering, and is suitable for iframe cross-domain communication in network target ranges.
Smart Images

Figure CN120729595A_ABST
Abstract
Description
Technical Field
[0001] The present invention belongs to the technical field of network security, and in particular relates to an iframe two-way encrypted communication method and system based on a network range. Background Art
[0002] Cyber Range is a technology that simulates and reproduces the network architecture, system equipment, business process operating status and operating environment in real cyberspace.
[0003] Cyber range data visualization uses graphical means to transform complex data generated during cyber attack and defense drills and security testing (such as attack traffic, exploit chains, and defense responses) into intuitive visual elements, helping users quickly understand the cyber confrontation landscape and key information. Cyber range data visualization rendering technology typically consists of two components: 2D charting libraries (echarts, D3.js) and 3D network rendering technology. The latter is typically developed by a third-party platform and ultimately integrated with the front-end via a URL. For cyber ranges, 3D network rendering typically displays the three-dimensional network topology of drill scenarios such as red-blue confrontations or special competitions, as well as some animated data generated by attacks and defenses. This data display requires communication with the front-end to obtain information. Therefore, encryption is used during communication to prevent sensitive data leakage and ensure communication integrity.
[0004] Traditional encryption methods are usually one-way authentication, which only verifies the information sent by the front-end to the third party. The third party does not filter or identify the information, which is prone to virus attacks or information acquisition errors. Traditional encryption lacks a digital signature mechanism, which cannot trace the source of the message or prevent the sender from denying it. Currently common encryption methods lack complete protection for information and are prone to malicious tampering during communication. Some encryption algorithms also use fixed keys, and historical communications can be cracked and decrypted. Symmetric encryption may reuse the same key, increasing the risk of leakage. Summary of the Invention
[0005] In response to the above-mentioned deficiencies in the prior art, the present application provides an iframe two-way encrypted communication method and system based on a network target range.
[0006] In the first aspect, the present application proposes an iframe bidirectional encrypted communication method based on a network range, comprising the following steps:
[0007] Step S1: After the subcomponent 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 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.
[0009] Step S3: The subcomponent uses the ECDH algorithm to derive a key based on the parent window public key and its own private key to generate a 256-bit AES-GCM session key, and processes the parent window public key and its own public key through 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 encryption channel is established.
[0011] Step S5: After the encryption channel is established, all cross-domain communication data is encrypted and transmitted using the AES-GCM algorithm. A 12-byte initialization vector and authentication tag are used in the encryption process. 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] Generate an ECDH key pair based on the P-384 elliptic curve asynchronously through the Web Crypto API. The ECDH key pair consists of a public key and a private key.
[0014] Register a message event listener and process all messages from the parent window through the this.handleParentMessage callback function to establish the basis for two-way secure communication;
[0015] Sends a child_ready type ready notification message to the parent window, using the parentOrigin parameter to limit the message target domain.
[0016] In some embodiments, step S2 includes:
[0017] The public key is converted into 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 through the postMessage API. The information transmission process adopts an asynchronous programming mode to ensure that the key generation and export operations are completed before the message is sent.
[0018] In some embodiments, step S3 includes: when the iframe end 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 usage as encryption or decryption operation, wherein the front end also derives the same session key through a symmetric process, and the front end and the iframe end reach a key consensus without transmitting the key itself.
[0019] In some embodiments, step S5 includes:
[0020] Front-end encryption and sending phase: Generate a session ID through CryptoJS.SHA256, use the Web Crypto API to generate a 12-byte random IV, encode the message through TextEncoder, encrypt it with AES-GCM using the pre-shared sessionKey, and finally send the ciphertext, IV, and session ID to the iframe through postMessage;
[0021] iframe-side processing phase: decrypts the message using the same algorithm and sessionKey, verifies the consistency of the session ID, processes the message, and re-encrypts the response;
[0022] Front-end decryption response phase: AES-GCM is used again to decrypt the data returned by the iframe. The entire process adopts an end-to-end encryption design, and IV is dynamically generated for each communication to prevent revisit attacks.
[0023] In some embodiments, step S5 also includes a 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 unique hash value of a fixed length for the string as a session ID, ensuring that each key exchange can generate an unpredictable session identifier.
[0024] In some embodiments, the AES-GCM performs dual protection by combining counter encryption and authentication mechanisms: crypto.getRandomValues is used to generate a 12-byte random IV during encryption, and a key stream is generated through AES-CTR mode to encrypt the plaintext; at the same time, Galois field multiplication is used to calculate a 128-bit authentication tag for the ciphertext and additional data, and the tag integrity is verified before decryption.
[0025] In the second aspect, the present application proposes an iframe two-way encrypted communication system based on a network range, comprising 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 subcomponent 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 for the parent window to send a handshake_init message containing its own public key in JWK format to the child component in response to the child_ready notification. The child component imports the parent window 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 for the subcomponent to use the ECDH algorithm to derive a key based on the parent window public key and its own private key to generate a 256-bit AES-GCM session key, and process the parent window public key and its own public key through the SHA256 hash algorithm to generate a sessionId that uniquely identifies the current session;
[0029] The secure channel establishment module is used for the subcomponent 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 encryption channel is established.
[0030] The encryption communication module is used to encrypt and transmit all cross-domain communication data using the AES-GCM algorithm after the encryption channel is established. A 12-byte initialization vector and authentication tag are used in the encryption process. The receiver ensures that the received message belongs to the correct communication session by verifying the sessionId.
[0031] In a third aspect, the present application proposes an electronic device, comprising a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor implements the steps of the above method when executing the computer program.
[0032] In a fourth aspect, the present application proposes a computer-readable storage medium, wherein the computer-readable storage medium stores a computer program, and when the computer program is executed by a processor, the steps of the above method are implemented.
[0033] Beneficial effects of the present invention:
[0034] In terms of data communication between the front-end and the third-party platform iframe, security is enhanced. ECDH key pairs are used to generate digital certificates, laying the foundation for identity authentication. A TCP handshake is then simulated to establish a reliable channel, and two-way identity authentication is achieved through two-way certificate verification and random number exchange to resist replay attacks. ECDH is then used to negotiate a shared key, and a dynamic session key is derived using the HKDF algorithm to ensure forward secrecy. Finally, AES-GCM is used for real-time data encryption and integrity verification, and a timed key rotation mechanism is used to continuously improve anti-leakage capabilities. The entire process integrates features such as quantum computing resistance, low resource consumption, and efficient transmission, providing an end-to-end secure communication paradigm for web applications. This prevents cross-session key confusion, ensures data confidentiality, integrity, and identity verifiability during cross-domain communication, and protects communication data from eavesdropping or tampering. BRIEF DESCRIPTION OF THE DRAWINGS
[0035] Figure 1 It is the overall flow chart of the present invention.
[0036] Figure 2 This is a system principle block diagram of the present invention. DETAILED DESCRIPTION
[0037] The following will describe exemplary embodiments of the present invention in more detail with reference to the accompanying drawings. Although exemplary embodiments of the present invention are shown in the accompanying drawings, it should be understood that the present invention can be implemented in various forms and should not be limited by the embodiments described herein; rather, these embodiments are provided to enable a more thorough understanding of the present invention and to fully convey the scope of the present invention to those skilled in the art.
[0038] In the first aspect, this application proposes an iframe two-way encrypted communication method based on a network range, such as Figure 1 As shown, the following steps are included:
[0039] Step S1: After the subcomponent 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] Generate an ECDH key pair based on the P-384 elliptic curve asynchronously through the Web Crypto API. The ECDH key pair consists of a public key and a private key.
[0042] Register a message event listener and process all messages from the parent window through the this.handleParentMessage callback function to establish the basis for two-way secure communication;
[0043] Sends a child_ready type ready notification message to the parent window, using the parentOrigin parameter to limit the message target domain.
[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 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.
[0045] In some embodiments, step S2 includes:
[0046] The public key is converted into 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 through the postMessage API. The information transmission process adopts an asynchronous programming mode to ensure that the key generation and export operations are completed before the message is sent.
[0047] Step S3: The subcomponent uses the ECDH algorithm to derive a key based on the parent window public key and its own private key to generate a 256-bit AES-GCM session key, and processes the parent window public key and its own public key through the SHA256 hash algorithm to generate a sessionId that uniquely identifies the current session;
[0048] In some embodiments, step S3 includes: when the iframe end 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 usage as encryption or decryption operation, wherein the front end also derives the same session key through a symmetric process, and the front end and the iframe end reach a key consensus 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 encryption channel is established.
[0050] Step S5: After the encryption channel is established, all cross-domain communication data is encrypted and transmitted using the AES-GCM algorithm. A 12-byte initialization vector and authentication tag are used in the encryption process. 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 encryption and sending phase: Generate a session ID through CryptoJS.SHA256, use the Web Crypto API to generate a 12-byte random IV, encode the message through TextEncoder, encrypt it with AES-GCM using the pre-shared sessionKey, and finally send the ciphertext, IV, and session ID to the iframe through postMessage;
[0053] iframe-side processing phase: decrypts the message using the same algorithm and sessionKey, verifies the consistency of the session ID, processes the message, and re-encrypts the response;
[0054] Front-end decryption response phase: AES-GCM is used again to decrypt the data returned by the iframe. The entire process adopts an end-to-end encryption design, and IV is dynamically generated for each communication to prevent revisit attacks.
[0055] In some embodiments, step S5 also includes a 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 unique hash value of a fixed length for the string as a session ID, ensuring that each key exchange can generate an unpredictable session identifier.
[0056] In some embodiments, the AES-GCM performs dual protection by combining counter encryption and authentication mechanisms: crypto.getRandomValues is used to generate a 12-byte random IV during encryption, and a key stream is generated through AES-CTR mode to encrypt the plaintext; at the same time, Galois field multiplication is used to calculate a 128-bit authentication tag for the ciphertext and additional data, and the tag integrity 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 communicating with the third-party platform iframe, listens to the message event 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 the public key and send it to the 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 consisting of a public and private key is generated using the P-384 curve, providing 192-bit security. The public key is then converted to the JWK (JSON Web Key) format using the exportKey method. This structured JSON format facilitates cross-domain key data transmission. Finally, a message containing the handshake type identifier, the public key JWK object, and the current timestamp is sent to the target iframe window using the postMessage API. The entire process utilizes an asynchronous programming pattern (async / await) to ensure that key generation and export operations are completed before message transmission. The inclusion of a timestamp effectively prevents replay attacks, while the use of a temporary key pair ensures forward security. This design lays the foundation for establishing an encrypted communication channel and is a critical first step in building a secure cross-domain communication system.
[0076] 3. iframe communication environment preparation
[0077] async init() {
[0078] / / Generate ECDH key pair for the child end
[0079] ecdhKeys = await crypto.subtle.generateKey(
[0080] { name: 'ECDH', namedCurve: 'P-384'},
[0081] true,
[0082] ['deriveKey'] )
[0084] / / Monitor parent window messages
[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, listens to the message event to receive information sent by the front-end, and processes the logic after receiving the information through handleParentMessage.
[0090] The above code mainly contains three key steps:
[0091] First, an ECDH key pair (including public and private keys) based on the P-384 elliptic curve is asynchronously generated through the Web Crypto API. This key pair will be used for subsequent key derivation operations. The namedCurve: 'P-384' specifies an elliptic curve with a 384-bit prime field to ensure security.
[0092] Then register the message event listener and process all messages from the parent window through the this.handleParentMessage callback function, which is the basis for achieving two-way secure communication;
[0093] Finally, it actively sends a ready notification message of the child_ready type to the parent window, and uses the parentOrigin parameter 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 to ensure that time-consuming operations such as key generation do not affect the main thread of the page. This establishes the necessary cryptographic foundation and environment preparation for subsequent secure handshakes and encrypted communications. 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 a NIST-standardized elliptic curve cryptography curve, using a 384-bit prime field and the specific parameter equation y² = x³ - 3x + b. Its core mechanism involves two parties generating a public-private key pair (the private key is a random number, and the public key = private key × base point G). After exchanging public keys, each party performs a point multiplication between their private key and the other's public key. Based on the associative property of elliptic curve point multiplication (d_A × d_B × G = d_B × d_A × G), the two parties generate a shared secret key. The x-coordinate of this secret key is processed by a key-determining function (KDF) and used as the session key. The entire process relies on the computational difficulty of the elliptic curve discrete logarithm problem for security.
[0096] The ECDH protocol generates a temporary key pair for each session (the private key is discarded upon use). Leveraging the computational irreversibility of the elliptic curve discrete logarithm problem, it ensures that even if an attacker obtains the long-term private key or intercepts historical communication data, they cannot decipher past session keys. Its core protection mechanisms include: ① dynamic key agreement (a new a·b·G shared secret is generated for each session); ② forward security design (temporary private keys are not stored); and ③ key derivation and mixing (HKDF combined with random number hashing). These three combined methods provide a dual guarantee of mathematical and engineering security, making historical session keys virtually impossible to decipher.
[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] / / The front end sends a handshake request
[0105] const publicKey = await crypto.subtle.exportKey(
[0106] 'jwk',
[0107] this.ecdhKeys.publicKey )
[0109] / / iframe-side derived key (logical symmetry)
[0110] sessionKey = await crypto.subtle.deriveKey(
[0111] { name: 'ECDH', public: parentPublicKey}, / / front-end public key
[0112] ecdhKeys.privateKey, / / 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}, / / iframe-side public key
[0120] this.ecdhKeys.privateKey, / / own private key
[0121] { name: 'AES-GCM', length: 256}, / / Derived key parameters
[0122] true, / / The key can be exported
[0123] ['encrypt', 'decrypt']
[0124] An end-to-end encrypted key exchange protocol based on the Web Crypto API, which adopts the Elliptic Curve Diffie-Hellman (ECDH) key agreement mechanism in modern cryptography.
[0125] In the front-end part, first use the P-384 curve (providing 192-bit security strength) to generate a temporary ECDH key pair, and use the exportKey method to convert the public key into JWK format for transmission;
[0126] After receiving the public key, the iframe performs the deriveKey operation on its own private key, using the mathematical properties of the ECDH algorithm to calculate the shared key. This process uses AES-GCM-256 as the derived key algorithm (providing quantum-safe 256-bit encryption strength) and explicitly specifies the key usage as encryption and decryption operations.
[0127] The frontend also derives the same session key through a symmetric process, ultimately achieving consensus on the key without transmitting the key itself. The entire process strictly adheres to the zero-trust principle. Temporary key pairs ensure forward security, the JWK format ensures standardized key transmission, and the choice of AES-GCM ensures both confidentiality and integrity. This design is suitable for micro-frontend architectures requiring secure cross-domain communication or scenarios with high security requirements. The asynchronous processing (async / await) of each step avoids blocking the UI thread.
[0128] Among them, the key exchange and derivation implementation process is to generate a key pair through the front-end and send a handshake request to the iframe. After 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 to tell the front-end that the key has been received and the key on the iframe side has been derived; similarly, after the front-end receives the request on the iframe side, the deriveKey method of the Web Crypto API is used to derive the front-end 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 Communications
[0130] / / ① Front-end encrypted sending information
[0131] / / Generate a 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 the encrypted message 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] const reply = await this.encryptMessage('Received message: ' + decrypted)<�
[0167] event.source.postMessage({
[0168] type: 'encrypted_message', [[ID=㰀7]]
[0169] ...reply,
[0170] sessionId
[0171] }, event.origin)
[0172] }
[0173] / / ③ Front-end receives the response from the iframe
[0174] const decrypted = await this.decryptMessage(
[0175] data.payload,
[0176] data.iv )
[0178] / / ⑤ Asynchronous function to decrypt the message async decryptMessage (payload, iv) {
[0179] const decrypted = await crypto.subtle.decrypt(
[0180] { name: 'AES-GCM', iv: new Uint8Array(iv)}, It should be noted that in the above translation, for the 7-digit tags - , they are preserved exactly as in the original text as required. Also, for the Chinese note in line 41, it is translated as " / / ③ Front-end receives the response from the iframe" while trying to keep the context and style as close as possible to the original. If there are any specific requirements or improvements needed regarding the translation of this note or the overall translation, please let me know.
[0181] this.sessionKey,
[0182] new Uint8Array(payload) )
[0184] return new TextDecoder().decode(decrypted)
[0185] }
[0186] Among them, the secure communication process based on the AES-GCM encryption algorithm is mainly divided into three core stages:
[0187] ① Front-end encryption and sending stage: Generate a session ID (based on the hash value of the public key) through CryptoJS.SHA256, use the Web Crypto API to generate a 12-byte random IV, encode the message through TextEncoder, and encrypt it with AES-GCM using the pre-shared sessionKey. Finally, send the ciphertext, IV, and session ID to the iframe through postMessage;
[0188] ② iframe end processing stage: Use the same algorithm and sessionKey to decrypt the message, verify the consistency of the session ID, process the message and re-encrypt the response;
[0189] ③ Front-end decryption response phase: AES-GCM is used again to decrypt the data returned by the iframe. The entire process utilizes end-to-end encryption. Dynamically generating an IV for each communication prevents replay attacks, and the session ID ensures communication context consistency. The AES-GCM algorithm provides 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] AES-GCM mode achieves dual protection by combining counter encryption and authentication mechanisms. During encryption, crypto.getRandomValues is used to generate a 12-byte random IV (ensuring uniqueness), which is then used in AES-CTR mode to generate a keystream for plaintext encryption. A Galois field multiplication is then used to calculate a 128-bit authentication tag (XORed with the encrypted IV and the GHASH hash result) from the ciphertext and appended data. During decryption, the tag integrity is verified before decryption, achieving an integrated encryption-authentication process. This design ensures data confidentiality while providing strong integrity verification. The randomness of the IV and the unforgeability of the tag enhance security.
[0191] JSON.stringify(data.publicKey) serializes the ECDH public key object into a JSON string, and then uses CryptoJS.SHA256 to generate a unique, fixed-length hash value from this string, which serves as the session ID. This ensures that each key exchange generates an unpredictable session identifier. The communication context strictly verifies that event.origin is bound to the preset parentOrigin. Combined with timestamps and the cross-domain postMessage mechanism, this establishes a secure channel between the parent and child iframe windows based on origin verification. Ultimately, encrypted communication is achieved using a derived AES-GCM session key.
[0192] Next, we will use the application scenario of cross-domain secure communication between browsers as an example to describe the above solution. Specifically:
[0193] 1. Initialization preparation phase
[0194] During this phase, after the subcomponents are loaded, an Elliptic Curve Diffie-Hellman (ECDH) key pair based on the P-384 curve is generated. This key pair is generated using the browser's window.crypto.subtle.generateKey interface, with a 384-bit key length that complies with NIST standards.
[0195] The child component registers a message listener via 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, the encrypted channel has not yet been established; only the basic communication environment has been prepared.
[0196] 2. Key exchange phase
[0197] After receiving the child_ready notification, the parent window constructs a handshake_init message and sends it to the child component through the postMessage interface. The message contains the parent window's ECDH public key, encoded in the JWK (JSON WebKey) format.
[0198] After receiving this message, the child component uses the crypto.subtle.importKey API to import the parent window's public key into a SubtleCrypto object for subsequent key derivation. At the same time, 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 between the two parties includes a timestamp field to prevent replay attacks. For example, the child component appends a timestamp when sending its own public key, 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 child component uses the ECDH algorithm to perform a key derivation operation on 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 sessionId that uniquely identifies the current communication session, the subcomponent concatenates the public keys of both parties (expressed in JWK format) and calculates its hash value using the SHA-256 hash function. This sessionId will be used to identify the current communication context in subsequent communications to ensure the correctness of message attribution.
[0203] 4. Secure channel confirmation phase
[0204] In this embodiment, to ensure the authenticity of both communicating parties, the child component digitally signs the coordinate information (x, y) and timestamp of its public key. The signature algorithm uses ECDSA, and the child component's private key is used to sign the following data: The signature result is returned to the parent window via the handshake_response message. Upon receiving this message, the parent window verifies the legitimacy of the signature using the child component's public key. If verification succeeds, the parent and child components set the communication connection status (connectionStatus) to true, indicating that the encrypted channel has been successfully established and that encrypted communication can begin.
[0205] 5. Encrypted communication phase
[0206] After the encrypted channel is established, all cross-domain communication messages are encrypted 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 sessionId of the current communication.
[0210] Before decryption, the receiver first verifies whether the sessionId is consistent with the current session. If not, 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 the authentication fails, the message is deemed to have been tampered with and is rejected.
[0212] Through the above-described embodiments, this method achieves end-to-end encrypted communication in a cross-domain browser environment. Through ECDH key exchange, session key derivation, identity 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 third-party iframe platform through ECDH key exchange and digital signatures, avoiding the risk of man-in-the-middle attacks. For dynamic key management, the P-384 curve is used to derive AES-256 keys, and temporary session keys are independently generated for each session. (This strategy uses crypto.subtle.generateKey to create an ECDHP-384 key pair. For key independence, each session generates a key pair through an independent handshake process (triggered by the handshake_init message). A basic lifecycle of 1 hour is set, and keys are immediately rotated when the encrypted data exceeds 4GB or a security risk is detected.) This provides forward secrecy. This design optimizes encryption efficiency, using asymmetric encryption for key negotiation (ECDH) and high-performance symmetric encryption (AES-GCM) for actual communication, achieving encryption and integrity verification. The solution also binds the communication context to a unique session ID generated by SHA-256 to prevent cross-session key confusion.
[0214] In the second aspect, this application proposes an iframe two-way encrypted communication system based on a network 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 encryption communication module;
[0215] The initialization preparation module is used to generate an elliptic curve key pair based on the P-384 curve after the subcomponent 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 for the parent window to send a handshake_init message containing its own public key in JWK format to the child component in response to the child_ready notification. The child component imports the parent window 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 for the subcomponent to use the ECDH algorithm to derive a key based on the parent window public key and its own private key to generate a 256-bit AES-GCM session key, and process the parent window public key and its own public key through the SHA256 hash algorithm to generate a sessionId that uniquely identifies the current session;
[0218] The secure channel establishment module is used for the subcomponent 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 encryption channel is established.
[0219] The encryption communication module is used to encrypt and transmit all cross-domain communication data using the AES-GCM algorithm after the encryption channel is established. A 12-byte initialization vector and authentication tag are used in the encryption process. The receiver ensures that the received message belongs to the correct communication session by verifying the sessionId.
[0220] In a third aspect, the present application proposes an electronic device, comprising a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor implements the steps of the above method when executing the computer program.
[0221] In a fourth aspect, the present application proposes a computer-readable storage medium, wherein the computer-readable storage medium stores a computer program, and when the computer program is executed by a processor, the steps of the above method are implemented.
[0222] Those skilled in the art can clearly understand that, for the convenience and brevity of description, only the division of the above-mentioned functional units and modules is used as an example for illustration. In actual applications, the above-mentioned functions can be distributed and completed by 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 embodiment can be integrated into one processing unit, or each unit can exist physically alone, or two or more units can be integrated into one unit. The above-mentioned integrated unit can be implemented in the form of hardware or in the form of software functional units. In addition, the specific names of the functional units and modules are only for the convenience of distinguishing each other, and are not used to limit the scope of protection of this application. The specific working process of the units and modules in the above-mentioned system can refer to the corresponding process in the aforementioned method embodiment, and will not be repeated here.
[0223] In the above embodiments, the description of each embodiment has its own focus. For parts that are not described or recorded in detail in a certain embodiment, reference can be made to the relevant description of other embodiments.
[0224] Those skilled in the art will appreciate that the units and algorithm steps of each example 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 performed in hardware or software depends on the specific application and design constraints of the technical solution. Professionals and technicians 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 the present disclosure, it should be understood that the disclosed apparatus / computer equipment and methods can be implemented in other ways. For example, the apparatus / computer equipment embodiments described above are merely schematic. For example, the division of modules or units is merely a logical function division. 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. Another point is that the mutual coupling or direct coupling or communication connection shown or discussed may be through some interfaces, indirect coupling or communication connection of the apparatus or unit, which may be electrical, mechanical or other forms.
[0226] Units described as separate components may or may not be physically separate, and 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 these units may be selected to achieve the purpose of this embodiment according to actual needs.
[0227] In addition, the functional units in the various embodiments of the present disclosure may be integrated into a single processing unit, or each unit may exist physically separately, or two or more units may be integrated into a single unit. The aforementioned integrated units may be implemented in the form of hardware or software functional units.
[0228] If the integrated module / unit is implemented as a software functional unit and sold or used as a standalone product, it can be stored in a computer-readable storage medium. Based on this understanding, the present disclosure can implement all or part of the process steps in the above-mentioned method embodiments by using a computer program to instruct the relevant hardware. The computer program can be stored in a computer-readable storage medium, and when executed by a processor, the computer program can implement the steps of each of the above-mentioned method embodiments. The computer program can include computer program code, which can be in source code form, object code form, executable file, or some intermediate form. Computer-readable media can include: any entity or device capable of carrying computer program code, recording media, USB flash drives, removable hard drives, magnetic disks, optical disks, computer memory, read-only memory (ROM), random access memory (RAM), electrical carrier signals, telecommunications signals, and software distribution media. It should be noted that the content included in computer-readable media can be appropriately increased or decreased based on the requirements of legislation and patent practice in a jurisdiction. For example, in some jurisdictions, based on legislation and patent practice, computer-readable media does not include electrical carrier signals and telecommunications signals.
[0229] The above are only preferred embodiments of the present invention. It should be pointed out that various modifications and improvements made by those skilled in the art without departing from the present technical solution should also be deemed to fall within the scope of protection required by this solution.
Claims
1. An iframe two-way encrypted communication method based on a network range, characterized by: The following steps are included: Step S1: After the subcomponent 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 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. Step S3: The subcomponent uses the ECDH algorithm to derive a key based on the parent window public key and its own private key to generate a 256-bit AES-GCM session key, and processes the parent window public key and its own public key through 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 encryption channel is established. Step S5: After the encryption channel is established, all cross-domain communication data is encrypted and transmitted using the AES-GCM algorithm. A 12-byte initialization vector and authentication tag are used in the encryption process. The receiver verifies the sessionId to ensure that the received message belongs to the correct communication session.
2. The method according to claim 1, wherein: The step S1 comprises: Generate an ECDH key pair based on the P-384 elliptic curve asynchronously through the Web Crypto API. The ECDH key pair consists of a public key and a private key. Register a message event listener and process all messages from the parent window through the this.handleParentMessage callback function to establish the basis for two-way secure communication; Sends a child_ready type ready notification message to the parent window, using the parentOrigin parameter to limit the message target domain.
3. The method according to claim 2, wherein: The step S2 comprises: The public key is converted into 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 through the postMessage API. The information transmission process adopts an asynchronous programming mode to ensure that the key generation and export operations are completed before the message is sent.
4. The method according to claim 3, wherein: The step S3 includes: when the iframe end 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 usage as encryption or decryption operation, wherein the front end also derives the same session key through a symmetric process, and the front end and the iframe end reach a key consensus without transmitting the key itself.
5. The method according to claim 4, characterized in that: The step S5 comprises: Front-end encryption and sending phase: Generate a session ID through CryptoJS.SHA256, use the Web Crypto API to generate a 12-byte random IV, encode the message through TextEncoder, encrypt it with AES-GCM using the pre-shared sessionKey, and finally send the ciphertext, IV, and session ID to the iframe through postMessage; iframe-side processing phase: decrypts the message using the same algorithm and sessionKey, verifies the consistency of the session ID, processes the message, and re-encrypts the response; Front-end decryption response phase: AES-GCM is used again to decrypt the data returned by the iframe. The entire process adopts an end-to-end encryption design, and IV is dynamically generated for each communication to prevent revisit attacks.
6. The method according to claim 5, characterized in that: The step S5 further includes a 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 unique hash value of a fixed length for the string as the 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 algorithm provides dual protection by combining counter encryption and authentication mechanisms: crypto.getRandomValues is used to generate a 12-byte random IV during encryption, and the key stream is generated through AES-CTR mode to encrypt the plaintext; a 128-bit authentication tag is calculated on the ciphertext and appended data using Galois field multiplication, and the tag integrity is verified before decryption.
8. The iframe two-way encrypted communication system based on the network range is characterized by: It includes an initialization preparation module, a key exchange module, a session key derivation module, a secure channel establishment module and an encryption communication module; The initialization preparation module is used to generate an elliptic curve key pair based on the P-384 curve after the subcomponent 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 for the parent window to send a handshake_init message containing its own public key in JWK format to the child component in response to the child_ready notification. The child component imports the parent window 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 for the subcomponent to use the ECDH algorithm to derive a key based on the parent window public key and its own private key to generate a 256-bit AES-GCM session key, and process the parent window public key and its own public key through the SHA256 hash algorithm to generate a sessionId that uniquely identifies the current session; The secure channel establishment module is used for the subcomponent 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 encryption channel is established. The encryption communication module is used to encrypt and transmit all cross-domain communication data using the AES-GCM algorithm after the encryption channel is established. A 12-byte initialization vector and authentication tag are used in the encryption process. The receiver ensures that the received message belongs to the correct communication session by verifying the sessionId.
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, the steps of the method according to any one of claims 1 to 7 are implemented.
10. A computer-readable storage medium, characterized in that: The computer-readable storage medium stores a computer program, and when the computer program is executed by a processor, the steps of the method according to any one of claims 1 to 7 are implemented.
Citation Information
Patent Citations
Monitoring flow scheduling system and method for network target range actual combat drilling scene
CN111526061A
Multi-network range collaborative data transmission method, device, equipment and medium
CN117811840A
Encryption tunnel communication method and device for path dynamic optimization
CN119583087A
Cited By
Secure communication method and device for dynamic mode encryption, medium and product
CN121356770A
Non-blocking ECDH shared key calculation method based on finite-state machine
CN121508855A
Encrypted inter-process communication method and system, computer equipment and medium
CN121959599A