Elegant API Encryption & Decryption: A Detailed Design and Implementation
This article presents a comprehensive solution for securing API interfaces by combining symmetric and asymmetric encryption, hashing, and signature techniques, illustrating the design, key exchange, data protection workflow, code implementation, and security analysis to prevent tampering, replay attacks, and unauthorized access.
Background and Goal
With the rapid development of network technology, data security issues have become increasingly prominent. To prevent crawlers, request tampering, replay attacks, and ensure data integrity, this solution integrates HTTPS principles with WeChat Pay encryption design to provide API encryption and decryption.
Design Overview
Symmetric Encryption: Uses the same key for encryption and decryption; fast and low‑cost, used for actual data transmission.
Asymmetric Encryption: Uses a public/private key pair; the public key encrypts the symmetric key, the private key decrypts it, ensuring secure key exchange.
Hash Algorithm: Produces a fixed‑length digest; any change in the original data results in a completely different hash.
Signature Algorithm: Private‑key signing and public‑key verification to guarantee data authenticity.
HTTPS Principle Overview
HTTPS (Hypertext Transfer Protocol Secure) secures communication by encrypting HTTP traffic with SSL/TLS and authenticating parties via certificates, ensuring confidentiality and integrity of data in transit.
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 private key; the merchant verifies using the platform public key.
Callback Decryption: The merchant decrypts encrypted callback data using the configured apiV3 key with AES‑256‑GCM.
Interface Encryption Design Flow
Key Exchange: The client encrypts the symmetric key with the server’s public key and sends the ciphertext; the server decrypts it with its private key.
Data Encryption: The client encrypts request parameters with the symmetric key; the server decrypts with the same key.
Data Hash (Signature): Before sending, the client computes a hash of the data and includes it; the server recomputes and compares to verify integrity.
Validity Check: The client adds a timestamp to the request; the server validates the timestamp to prevent replay attacks.
Technical Implementation
1. Key Generation & Management: Generate an asymmetric key pair; the server stores the private key, and the client can periodically fetch the public key (with risk of leakage).
2. Algorithm Selection: Symmetric encryption uses AES; asymmetric encryption uses RSA; hash algorithms include SHA‑256 or MD5; signatures use RSA‑SHA256. The following Java snippet (Hutool library) demonstrates key handling, encryption, decryption, and signing:
// Symmetric key
String key = "key";
AES aes = SecureUtil.aes(key.getBytes());
String ciphertext = aes.encryptBase64(content);
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);
// Hash and sign
Digester sha256 = new Digester(DigestAlgorithm.SHA256);
System.out.println(sha256.digestHex(data));
Sign privateSign = SecureUtil.sign(SignAlgorithm.SHA256withRSA, privateKey, null);
String sign = new String(Base64.getEncoder().encode(privateSign.sign(data)));
System.out.println("Signature: " + sign);
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 query string and body parameters, concatenate queryString, timestamp, plaintext symmetric key, and body, then hash with SHA‑256 to obtain sign, which is placed in the request header.
4. Parameter Transmission: ek carries the asymmetric‑encrypted symmetric key, ts carries the timestamp, and sign carries the SHA‑256 signature.
Backend Processing Steps
Validate request timestamp from the ts header.
Decrypt the symmetric key using the server’s private key from the ek header.
Re‑construct the signed string (queryString + timestamp + plaintext key + body) and compute its SHA‑256 hash; compare with the sign header.
Decrypt query string and body parameters with the plaintext symmetric key.
Encrypt the response payload with the symmetric key and return the Base64 ciphertext.
Security Analysis
The hybrid use of symmetric and asymmetric encryption ensures both confidentiality and performance. Security considerations include protecting the client‑side public key and preventing key leakage.
Anti‑tamper: All request parameters are signed; without the public key, they cannot be altered.
Anti‑crawler: Signed and encrypted parameters make it impossible to simulate legitimate client requests.
Anti‑replay: Timestamps are signed and validated; short‑term replay is mitigated, and longer‑term replay could be blocked via server‑side caching.
Common Questions
Why reference HTTPS? HTTPS combines symmetric and asymmetric encryption, offering high security while meeting efficiency requirements.
What if only symmetric encryption is used? The client environment is insecure; exposure of the symmetric key would render encryption ineffective.
What if only asymmetric encryption is used? RSA supports only short messages (≈117 bytes) and is computationally slow; it is therefore unsuitable for bulk data.
Is signing still necessary when parameters are encrypted? Yes, because not all interfaces are encrypted in production; signing prevents tampering and replay.
Why not use RSA‑SHA256 for signing? RSA‑SHA256 requires a private key for signing and a public key for verification; storing the private key on the client would increase maintenance complexity.
How to ensure efficiency with both encryption types? Only the symmetric key is processed asymmetrically; the bulk data uses symmetric encryption, keeping performance comparable to pure symmetric schemes.
Is the scheme absolutely secure? No; if the client is compromised, an attacker can simulate requests. Absolute security is unattainable for client‑side code.
Illustrations
HTTPS workflow diagram:
WeChat Pay encryption diagram:
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.
