How to Secure API Calls with Hybrid Symmetric‑Asymmetric Encryption and Signatures
This article walks through a complete API protection scheme that combines HTTPS fundamentals, symmetric AES encryption, RSA key exchange, SHA‑256 hashing, and custom signature logic to prevent crawling, request tampering, and replay attacks while maintaining high performance.
Background and Goal
With rapid network development, data‑security issues such as crawlers, request tampering, replay attacks, and integrity verification have become critical. The proposed solution integrates HTTPS principles and WeChat Pay encryption techniques, using symmetric encryption for data transfer, asymmetric encryption for key exchange, and hash‑based signatures for integrity.
Design Overview
Cryptographic Primitives
Symmetric encryption: Same key for encrypt/decrypt; fast but requires secure key transport. Used for actual data payload.
Asymmetric encryption: Public‑key encrypts, private‑key decrypts; secures key exchange but slower, unsuitable for long texts. Used to encrypt the symmetric key.
Hash algorithm: Produces fixed‑length digest; any change in input yields a completely different output.
Signature algorithm: Private key signs data; public key verifies the signature.
HTTPS Principle
HTTPS (Hypertext Transfer Protocol Secure) encrypts HTTP traffic via SSL/TLS and authenticates parties with certificates, ensuring confidentiality and integrity.
WeChat Pay Encryption
Request signature: Each request is signed with the merchant’s RSA‑SHA256 private key; WeChat Pay verifies the signature.
Callback verification: WeChat Pay signs callbacks with its private key; the merchant verifies using the public key.
Callback decryption: Merchant decrypts AES‑256‑GCM encrypted data using the configured apiV3 key.
Interface Encryption Design
Key exchange: Client encrypts the symmetric key with the server’s public key and sends the ciphertext; server decrypts with its private key.
Data encryption: Client encrypts request data with the symmetric key; server decrypts with the same key.
Hash (signature) generation: Client computes a hash of the data, sends the hash with the payload; server recomputes and compares to verify integrity.
Timestamp validation: Client includes current time; server checks the timestamp to reject replayed requests.
Technical Implementation
1. Key Generation and Management
Generate an RSA key pair; the server stores the private key, while the client can fetch the public key (preferably stored encrypted in LocalStorage).
2. Algorithm Selection
Symmetric: AES; Asymmetric: RSA; Hash: SHA‑256 (or MD5 for legacy); Signature: RSA‑SHA256. Example using Hutool library:
// Symmetric key
String key = "key";
AES aes = SecureUtil.aes(key.getBytes());
// Encryption
String ciphertext = aes.encryptBase64(content);
// Decryption
String result = aes.decryptStr(ciphertext);
// Asymmetric public key
String publicKey = "xxxxxxx";
RSA rsa = new RSA(null, publicKey);
String ciphertextKey = rsa.encryptBase64(key, KeyType.PublicKey);
// Asymmetric private key
String privateKey = "xxxxxxx";
RSA rsa2 = new RSA(privateKey, null);
String decryptedKey = rsa2.encryptBase64(ciphertextKey, KeyType.PrivateKey);
// SHA‑256 digest
Digester sha256 = new Digester(DigestAlgorithm.SHA256);
System.out.println(sha256.digestHex(data));
// Signature creation
Sign privateSign = SecureUtil.sign(SignAlgorithm.SHA256withRSA, privateKey, null);
String sign = new String(Base64.getEncoder().encode(privateSign.sign(data)));
System.out.println("Signature: " + sign);
// Signature verification
Sign publicSign = SecureUtil.sign(SignAlgorithm.SHA256withRSA, null, publicKey);
System.out.println(publicSign.verify(data.getBytes(), Base64.getDecoder().decode(sign.getBytes())));3. Signature Rule
After encrypting queryString and body, concatenate queryString, timestamp, plaintext symmetric key, and body in order, then hash with SHA‑256 to obtain the signature (sign) placed in the request header.
4. Parameter Transmission
ek (encrypt‑key): RSA‑encrypted symmetric key.
ts: Timestamp.
sign: SHA‑256 signature.
Example request construction:
url?ciphertext=xxxxx
body:xxxxxxxx5. Backend Processing Steps
Validate request timestamp (ts) against a freshness window.
Decrypt ek using the server’s private RSA key to obtain the symmetric key.
Re‑create the signature by concatenating queryString, ts, symmetric key, and body, then hash with SHA‑256; compare with the sign header.
Decrypt queryString and body using the symmetric key.
Encrypt the response payload with the symmetric key (Base64) and return to the client.
Common Questions
Why reference HTTPS? HTTPS combines symmetric and asymmetric encryption, offering high security and acceptable performance.
What if only symmetric encryption is used? The client becomes a weak point; exposure of the key compromises security.
What if only asymmetric encryption is used? RSA supports only short messages (≈117 bytes) and is much slower.
Is signing still needed when data is encrypted? Yes, to protect against tampering and replay even if not all endpoints encrypt data.
Why not use RSA‑SHA256 for signatures? It requires a private key on the client side, increasing maintenance; the current approach uses SHA‑256 with the symmetric key embedded to simulate a signature.
How to protect the public key stored on the client? Use code obfuscation, split and encrypt the key, and rely on the fact that each request generates a fresh symmetric key.
Does mixing symmetric and asymmetric encryption affect performance? The bulk data is encrypted symmetrically; asymmetric operations only handle the short symmetric key, so overall performance remains comparable to pure symmetric encryption.
Is the scheme absolutely secure? No; if the client is compromised, an attacker can mimic legitimate requests.
Security Analysis
The hybrid design leverages the speed of AES and the key‑exchange safety of RSA, providing confidentiality, integrity, and replay protection. However, the client‑side public key must be safeguarded through obfuscation and regular rotation.
Anti‑tampering: All parameters are signed; without the private key, an attacker cannot modify them.
Anti‑crawling: Encrypted and signed parameters prevent automated scraping; encrypted responses cannot be interpreted without the symmetric key.
Anti‑replay: Timestamps are signed and validated; short‑term replay can be mitigated with server‑side caching if needed.
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.
Architect
Professional architect sharing high‑quality architecture insights. Topics include high‑availability, high‑performance, high‑stability architectures, big data, machine learning, Java, system and distributed architecture, AI, and practical large‑scale architecture case studies. Open to ideas‑driven architects who enjoy sharing and learning.
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.
