Designing Secure API Encryption with HTTPS and WeChat Pay Principles
This article outlines a comprehensive API security solution that combines symmetric and asymmetric encryption, HTTPS fundamentals, and WeChat Pay cryptographic practices, detailing design, implementation, key management, parameter handling, backend processing, and security analysis to protect against tampering, replay, and crawling.
Background and Goal
To protect API interfaces from crawlers, request tampering, replay attacks and to verify data integrity, the solution combines HTTPS principles with WeChat Pay encryption design. It uses symmetric encryption for data transmission, asymmetric encryption for key exchange, SHA‑256 hashing, and RSA‑SHA256 signatures.
Design Overview
Cryptographic Primitives
Symmetric encryption : Fast, low‑cost encryption using a shared secret key (AES). Used for encrypting request/response payloads.
Asymmetric encryption : RSA public‑private key pair. The client encrypts the symmetric key with the server’s public key; the server decrypts it with its private key.
Hash algorithm : SHA‑256 produces a fixed‑length digest; any change in the input yields a completely different digest.
Signature algorithm : RSA‑SHA256 signs data with a private key and verifies with the corresponding public key.
HTTPS Principle
HTTPS (Hypertext Transfer Protocol Secure) secures communication by establishing an SSL/TLS channel, encrypting HTTP traffic and using certificates for identity verification.
WeChat Pay Encryption
Request signature : Each request is signed with RSA‑SHA256 using the merchant API certificate private key; WeChat Pay verifies the signature.
Callback verification : WeChat Pay signs callbacks with its platform certificate private key; the merchant verifies using the platform public key.
Callback decryption : Merchants decrypt callback data with the configured apiV3 key using AES‑256‑GCM.
Interface Encryption Design
Key exchange : Client encrypts the symmetric key with the server’s public key (header ek); server decrypts with its private key.
Data encryption : Client encrypts request data with the symmetric key; server decrypts with the same key.
Data hash (signature) : Client computes a SHA‑256 hash of the concatenated queryString, timestamp, plaintext symmetric key, and body; the hash is sent as sign header. Server recomputes and compares.
Validity check : Timestamp ( ts) is included and validated to prevent replay attacks.
Technical Implementation
1. Key Generation and Management
Generate an RSA key pair; store the private key securely on the server. The client obtains the server’s public key (e.g., via a trusted endpoint) and caches it locally.
2. Encryption Algorithm Selection (Java/Hutool example)
// Symmetric key (AES)
String key = "key";
AES aes = SecureUtil.aes(key.getBytes());
String ciphertext = aes.encryptBase64(content);
String result = aes.decryptStr(ciphertext);
// Asymmetric public key (RSA)
String publicKey = "xxxxxxx";
RSA rsa = new RSA(null, publicKey);
String ciphertextKey = rsa.encryptBase64(key, KeyType.PublicKey);
// Asymmetric private key (RSA)
String privateKey = "xxxxxxx";
RSA rsa2 = new RSA(privateKey, null);
String decryptedKey = rsa2.decryptStr(ciphertextKey, KeyType.PrivateKey);
// SHA‑256 hash
Digester sha256 = new Digester(DigestAlgorithm.SHA256);
System.out.println(sha256.digestHex(data));
// Signature (RSA‑SHA256)
Sign privateSign = SecureUtil.sign(SignAlgorithm.SHA256withRSA, privateKey, null);
String sign = new String(Base64.getEncoder().encode(privateSign.sign(data)));
Sign publicSign = SecureUtil.sign(SignAlgorithm.SHA256withRSA, null, publicKey);
System.out.println(publicSign.verify(data.getBytes(), Base64.getDecoder().decode(sign.getBytes())));3. Signature Construction
After encrypting the query string and body, concatenate queryString, ts, the plaintext symmetric key, and the encrypted body in that order. Compute a SHA‑256 hash of the concatenated string; the resulting hex digest is the sign value placed in the request header.
4. Parameter Transmission
ek : RSA‑encrypted symmetric key.
ts : Unix timestamp.
sign : SHA‑256 hash as described.
Example request URL: https://api.example.com/resource?ciphertext=xxxxx with body containing the Base64‑encoded encrypted payload.
5. Backend Processing Flow
Validate timestamp : Reject requests where ts is outside an acceptable window.
Decrypt symmetric key : Use the server’s RSA private key to decrypt ek and obtain the plaintext AES key.
Verify signature : Re‑assemble queryString, ts, plaintext key, and body; compute SHA‑256 and compare with the sign header.
Decrypt payload : Decrypt the query string and body using the obtained AES key.
Encrypt response : After processing, encrypt the response data with the same AES key and return the Base64 ciphertext.
Security Analysis
Anti‑tampering : All request parameters are signed; without the client’s private key, parameters cannot be altered.
Anti‑crawler : Encrypted and signed parameters prevent automated replay; encrypted responses cannot be interpreted without the symmetric key.
Anti‑replay : Timestamps are signed and validated, rejecting stale requests. Short‑term replay can be mitigated with server‑side caching if needed.
Common Questions
Why reference HTTPS? HTTPS combines symmetric and asymmetric encryption, providing strong security while maintaining performance.
Problems with only symmetric encryption? The client key must be stored on the client; if compromised, the entire encryption scheme collapses.
Problems with only asymmetric encryption? RSA can encrypt only short messages (~117 bytes) and is computationally expensive.
Is signing still needed when parameters are encrypted? Yes; not all production interfaces are encrypted, and signatures protect against tampering and replay.
Why not use RSA‑SHA256 for signing? RSA‑SHA256 requires a private key on the client for signing, which would add another key pair to manage. The current design uses SHA‑256 hashing with the plaintext symmetric key mixed in, achieving similar protection without extra key management.
How to protect the client‑side public key? Use code obfuscation, store the key in encrypted segments, and avoid hard‑coding plain keys.
Performance impact of mixed encryption? Bulk data is encrypted symmetrically; asymmetric operations only handle the symmetric key, so overall performance is comparable to pure symmetric encryption.
Is the scheme absolutely secure? No; if the client is compromised, an attacker can forge requests. There is no perfect client‑side security solution.
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.
