Securing API Calls with Hybrid Symmetric‑Asymmetric Encryption and HTTPS Principles
This article presents a comprehensive design for API request and response protection that combines symmetric and asymmetric encryption, HTTPS fundamentals, and WeChat Pay specific cryptographic mechanisms, detailing key exchange, data signing, parameter handling, implementation code, common pitfalls, and a security analysis.
Background & Goal
Rapid network development has increased data‑security risks such as crawling, request tampering, replay attacks, and integrity verification. The solution protects API interfaces by combining HTTPS principles with WeChat Pay encryption, using symmetric encryption for data, asymmetric encryption for key exchange, and a hash‑based signature for integrity.
Design Overview
Symmetric encryption (AES)
Asymmetric encryption (RSA)
Hash algorithm (SHA‑256)
Signature algorithm (SHA256‑with‑RSA simulated by hashing the concatenated parameters)
HTTPS principle for secure transport
WeChat Pay encryption flow
Cryptographic Algorithms
Symmetric encryption: Same key encrypts and decrypts data; fast but requires secure key transmission.
Asymmetric encryption: Public key encrypts data (or a symmetric key) and private key decrypts; slower and unsuitable for large payloads.
Hash algorithm: Produces a fixed‑length digest; any change in input yields a completely different output.
Signature algorithm: Private key signs data; public key verifies the signature.
HTTPS Overview
HTTPS (Hypertext Transfer Protocol Secure) encrypts HTTP traffic with SSL/TLS and authenticates parties via certificates, ensuring confidentiality and integrity.
WeChat Pay Encryption Principles
Request signature: Each request is signed with the merchant API certificate private key using RSA‑SHA256; WeChat Pay verifies the signature.
Callback verification: WeChat Pay signs each callback with its platform certificate private key; the merchant verifies using the platform public key.
Callback decryption: The merchant decrypts encrypted callback data with the configured apiV3 key using AES‑256‑GCM.
Interface Encryption Design
Key exchange: The client encrypts a freshly generated symmetric key with the server’s public RSA key and sends the ciphertext ( ek) to the server. The server decrypts it with its private key to obtain the plaintext symmetric key.
Data encryption: The client encrypts request parameters (query string and body) with the symmetric key using AES‑256‑GCM; the server decrypts with the same key.
Data hash (signature): After encryption, the client concatenates queryString, timestamp ( ts), the plaintext symmetric key, and the encrypted body, then hashes the result with SHA‑256 to produce sign, which is placed in the request header.
Replay protection: The client includes a current timestamp; the server validates that the timestamp falls within an acceptable window.
Technical Implementation
1. Key Generation & Management
Generate an RSA key pair (e.g., with OpenSSL). Store the private key securely on the server. The public key can be distributed to clients (e.g., via a secure endpoint) and cached locally.
2. Encryption Algorithm Selection (Java Hutool example)
// Symmetric key (AES)
String key = "key";
AES aes = SecureUtil.aes(key.getBytes());
// Encrypt data
String ciphertext = aes.encryptBase64(content);
// Decrypt data
String result = aes.decryptStr(ciphertext);
// Asymmetric public key (RSA)
String publicKey = "xxxxxxx";
RSA rsaPub = new RSA(null, publicKey);
// Encrypt symmetric key
String ciphertextKey = rsaPub.encryptBase64(key, KeyType.PublicKey);
// Asymmetric private key (RSA)
String privateKey = "xxxxxxx";
RSA rsaPriv = new RSA(privateKey, null);
// Decrypt symmetric key
String plainKey = rsaPriv.decryptStr(ciphertextKey, KeyType.PrivateKey);
// SHA‑256 hash
Digester sha256 = new Digester(DigestAlgorithm.SHA256);
System.out.println(sha256.digestHex(data));
// Simulated signature (hash of concatenated parameters)
Sign privateSign = SecureUtil.sign(SignAlgorithm.SHA256withRSA, privateKey, null);
String sign = Base64.getEncoder().encodeToString(privateSign.sign(data));
System.out.println("签名:" + sign);
Sign publicSign = SecureUtil.sign(SignAlgorithm.SHA256withRSA, null, publicKey);
System.out.println(publicSign.verify(data.getBytes(), Base64.getDecoder().decode(sign)));3. Signature Rules
After encrypting queryString and body, concatenate queryString + ts + plaintext symmetric key + body, then compute SHA‑256. The resulting hash is the sign header.
4. Parameter Transmission
ek: RSA‑encrypted symmetric key. ts: Unix timestamp (seconds). sign: SHA‑256 hash signature.
Example request URL: https://api.example.com/endpoint?ciphertext=xxxxx with a JSON body containing the base64‑encoded encrypted payload.
Backend Processing Steps
Request validity verification: Extract ts from headers and ensure it is within the allowed time window (e.g., ±5 minutes).
Decrypt symmetric key: Use the server’s RSA private key to decrypt ek, obtaining the plaintext symmetric key.
Signature verification: Re‑assemble queryString, ts, symmetric key, and body; hash with SHA‑256 and compare to the sign header.
Decrypt parameters: Decrypt the encrypted query string and body using the symmetric key (AES‑256‑GCM).
Encrypt response: After processing, encrypt the response data with the same symmetric key and return the base64 ciphertext.
Common Questions
Why reference HTTPS? HTTPS combines symmetric and asymmetric encryption, providing strong security while maintaining performance.
What if only symmetric encryption is used? The client environment is insecure; exposure of the symmetric key compromises the entire communication.
What if only asymmetric encryption is used? RSA can encrypt only short messages (~117 bytes) and is computationally expensive.
Is signing still needed when parameters are encrypted? Yes, because not all production interfaces are encrypted; signing protects against tampering and replay.
Why not use RSA‑SHA256 for signing? RSA‑SHA256 requires a private key on the client, adding key‑pair management overhead. A SHA‑256 hash that includes the plaintext symmetric key provides a lightweight simulated signature.
How to protect the public key? Apply code obfuscation, avoid hard‑coding the key (store it in encrypted segments), and rely on per‑request generation of a fresh symmetric key.
Does mixing symmetric and asymmetric encryption affect performance? No; only the symmetric key is processed asymmetrically, so overall performance remains close to pure symmetric encryption.
Is the scheme absolutely secure? No. If the client is compromised, an attacker can mimic the client. There is currently no perfect client‑side encryption solution.
Security Analysis
The hybrid approach leverages the speed of symmetric encryption for bulk data and the key‑exchange security of asymmetric encryption. It provides confidentiality, integrity, anti‑tampering, anti‑crawling, and replay‑attack protection. Primary risk factors are the exposure of the client‑side public key and potential client compromise.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
