Information Security 15 min read

Design and Implementation of API Encryption Using HTTPS and WeChat Pay Principles

This article presents a comprehensive design and implementation guide for securing API interfaces by combining HTTPS fundamentals with WeChat Pay encryption techniques, detailing symmetric and asymmetric encryption, hashing, signature verification, key exchange, parameter handling, and backend processing to protect against tampering, replay attacks, and data leakage.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Design and Implementation of API Encryption Using HTTPS and WeChat Pay Principles

1. Background and Objectives

With the rapid development of network technology, data security issues have become increasingly prominent. To prevent crawlers, request tampering, replay attacks, and to verify data integrity, this solution combines HTTPS principles with WeChat Pay encryption design, using symmetric encryption, asymmetric encryption, and signature techniques to provide a practical API encryption scheme.

2. Solution Design

Symmetric Encryption, Asymmetric Encryption, Hash Algorithms, Signature Verification

Symmetric Encryption: Uses the same key for encryption and decryption, offering fast speed and low computational cost; the key transmission security is the main concern. It is used for actual data transmission in this scheme.

Asymmetric Encryption: Uses a public‑private key pair; the public key encrypts data, the private key decrypts it. It secures key exchange but is slower, so it is used only to encrypt the symmetric key.

Hash Algorithms: Produce a fixed‑length digest regardless of input length; any slight change in the original data results in a completely different digest.

Signature Algorithms: Typically involve signing data with a private key and verifying the signature with the corresponding public key.

Overview of HTTPS

HTTPS ( Hypertext Transfer Protocol Secure ) is a protocol for secure communication over computer networks. It leverages SSL/TLS to encrypt HTTP traffic and uses certificates for identity verification, ensuring confidentiality and integrity of data transmission.

WeChat Pay Encryption/Decryption 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 it using the platform public key.

Callback Decryption: The merchant decrypts encrypted callback data using the configured apiV3 key with AES‑256‑GCM.

API Encryption/Decryption Design Approach

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 to obtain the plaintext symmetric key.

Data Encryption: The client encrypts request data with the symmetric key and sends it; the server decrypts using the same key.

Data Hash (Signature): Before sending, the client computes a hash of the data and includes it; the server recomputes the hash and compares to verify integrity.

Data Validity Check: The client includes the current timestamp; the server compares it with its own time to prevent replay attacks.

3. Technical Implementation

1. Key Generation and Management

Generate an asymmetric key pair with a tool; the server stores the private key. The client can periodically fetch the public key from the server (with risk of leakage) and store it in LocalStorage.

2. Encryption Algorithm Selection

Symmetric encryption can use AES; asymmetric encryption can use RSA. Hash algorithms may be SHA‑256 or MD5, and signature algorithms can be RSA‑SHA256, etc. Example code using Hutool library:

// 对称密钥
String key = "key";
AES aes = SecureUtil.aes(key.getBytes());
// 加密
String ciphertext = aes.encryptBase64(content);
// 解密
String result = aes.decryptStr(ciphertext);
// 非对称公钥
String publicKey = "xxxxxxx";
// 对称密钥
String key = "key";
RSA rsa = new RSA(null, publicKey);
// 对对称密钥进行加密
String ciphertextKey = rsa.encryptBase64(key, KeyType.PublicKey);

// 非对称私钥
String privateKey = "xxxxxxx";
RSA rsa2 = new RSA(privateKey, null);
// 对加密的对称密钥进行解密
String key = rsa2.encryptBase64(ciphertextKey, KeyType.PrivateKey);
String data = "测试";
Digester sha256 = new Digester(DigestAlgorithm.SHA256);
System.out.println(sha256.digestHex(data));
// 暂不考虑
String publicKey = "xxxxx";
String privateKey = "xxxxx";
String data = "测试";
Sign privateSign = SecureUtil.sign(SignAlgorithm.SHA256withRSA, privateKey, null);
String sign = new String(Base64.getEncoder().encode(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.getBytes())));

3. Signature Rules

After encrypting queryString and body parameters, concatenate queryString, timestamp, plaintext symmetric key, and body in order, then hash the concatenated string with SHA‑256 to obtain the signature (sign) and place it in the request header.

4. Parameter Transmission

ek (encrypt‑key): xxxxxxx (asymmetric‑encrypted symmetric key)

ts: xxxxxxx (timestamp)

sign: xxxxxxx (signature)

Combine the request parameter queryString into the format "param1=value1&param2=value2" and encrypt it with the symmetric key to obtain ciphertext=xxxxx , then append it to the URL.

GET requests use the encrypted query string; POST bodies are encrypted with the symmetric key and transmitted as Base64.

url?ciphertext=xxxxx
body:xxxxxxxx

5. Backend Processing

Request Validity Verification: Retrieve the ts header, check whether the timestamp is within an acceptable range.

Decrypt Symmetric Key: Use the server's private key to decrypt the ek header and obtain the plaintext symmetric key.

Signature Verification: Concatenate queryString, timestamp, plaintext symmetric key, and body, hash with SHA‑256, and compare the result with the sign header.

Decrypt Parameters: Use the symmetric key to decrypt the query string and body.

Encrypt Response: After processing, encrypt the response data with the symmetric key, encode it as Base64, and return to the client.

4. Frequently Asked Questions

Q: Why reference HTTPS when designing API encryption?

A: HTTPS combines symmetric and asymmetric encryption, providing high security while meeting efficiency requirements.

Q: What problems arise if only symmetric encryption is used?

A: The client environment is insecure; if the key is exposed, encryption becomes ineffective.

Q: What problems arise if only asymmetric encryption is used?

Asymmetric encryption cannot handle long texts (RSA supports up to 117 bytes).

Performance is too slow.

Q: If the request parameters are already encrypted, is a signature still necessary?

A: Yes. Not every interface is encrypted in production, but all interfaces need protection against tampering and replay.

Q: Why not use RSA‑SHA256 for the signature algorithm?

RSA‑SHA256 can only be signed with a private key and verified with a public key.

The client only stores the public key; using this algorithm would require an additional asymmetric key pair, increasing maintenance cost.

We currently simulate a signature with SHA‑256 hash that incorporates the plaintext symmetric key, which also prevents forgery.

Q: If the public key stored on the client is leaked, how is security ensured?

Obfuscate and compress front‑end code.

Do not store the public key directly; split and encrypt it.

Even if the public key is exposed, the symmetric key is generated per request, so captured traffic cannot be decrypted.

Q: How is efficiency maintained when using both symmetric and asymmetric encryption?

A: The actual request parameters and response data are encrypted symmetrically; asymmetric encryption is only used for the symmetric key, so overall efficiency is comparable to pure symmetric encryption.

Q: Is this scheme absolutely secure? Is there an absolutely secure encryption solution?

No. If the client is compromised, an attacker can simulate legitimate requests.

Currently there is no absolutely secure solution; any compromised client can be used to forge requests.

5. Security Analysis

This scheme leverages the advantages of both symmetric and asymmetric encryption to ensure data transmission security while maintaining high performance, though the security of the client‑side public key must be considered.

Anti‑tampering: All request parameters are signed; without the client’s public key, parameters cannot be altered.

Anti‑scraping: Signed and encrypted request parameters prevent attackers from mimicking client requests; encrypted responses cannot be decrypted even if captured.

Anti‑replay: A timestamp is included in the request header and also signed, preventing replay attacks. Short‑term replay may still be possible, but can be mitigated with server‑side caching if needed.

Source: juejin.cn/post/7358368402795692082

Backend Technical Community

Build a high‑quality technical exchange community; developers, technical recruiters, and those interested in sharing job referrals are welcome to join.

Maintain civil discourse, focusing on technical exchange , job referrals , and industry discussion .

Advertisements are prohibited; do not trust private messages to avoid scams.

Add me as a friend, I will invite you to the group.

EncryptionAPI securityHTTPSSignatureWeChat Payasymmetric encryptionSymmetric Encryption
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.