RSA-based Signature Authentication
Differences from MD5 Signing
Merchants already integrated with MD5 signing can use the table below to quickly understand the differences:
| Item | MD5 Signing | RSA2048 Signing |
|---|---|---|
| Algorithm | MD5 digest (symmetric key) | SHA256withRSA (asymmetric key pair) |
| Keys | apiKey assigned by the platform, shared by both parties | Merchant generates its own key pair and submits only the public key to the platform; the platform public key is delivered by the platform |
| Request content to sign | Request body + apiKey | UTF-8 bytes of (Timestamp + ":" + request body), no key appended |
| Request headers | MerchantId, Sign | MerchantId, Sign, Timestamp (Unix milliseconds, participates in signing) |
| Signature format | 32-character hexadecimal string | Standard Base64, 344 characters |
| Webhook content to sign | Webhook body + apiKey | UTF-8 bytes of (Timestamp + ":" + webhook body), signed with the platform private key |
| Webhook headers | MerchantId, Sign | MerchantId, Sign, Timestamp |
| Verification failure error code | Sign_verify_error | SIGN_ERROR |
1. Algorithm Overview
RSA2048 is a digital signature scheme based on RSA asymmetric cryptography. The parameters are fixed as follows:
| Item | Convention |
|---|---|
| Signature algorithm | SHA256withRSA (RSASSA-PKCS1-v1_5, commonly known as RSA2) |
| Hash algorithm | SHA-256 |
| Key length | 2048 bits |
| Signature encoding | Standard Base64 (256-byte signature → 344 characters, not URL-Safe Base64) |
Key direction overview:
| Scenario | Signer (holds private key) | Verifier (holds public key) |
|---|---|---|
| Merchant → Platform API request | Merchant (merchant private key) | Platform (merchant public key) |
| Platform → Merchant order webhook | Platform (platform private key) | Merchant (platform public key) |
2. Integration Process
① Merchant generates its own RSA-2048 key pair (see Section 3)
② Merchant submits the [merchant public key PEM] to the platform (entered via business/operations console), and keeps the private key safe
③ Platform generates the platform key pair and delivers the [platform public key PEM] to the merchant (for webhook verification)
④ The platform enables RSA2048 signing for the merchant
⑤ Merchant implements request signing and webhook verification per this document and runs joint tests
⑥ Integration complete, live transactions beginNotes:
- Request signing and webhook verification use the same algorithm: once the platform enables
RSA2048for the merchant, both inbound request verification and outbound webhook signing use RSA2048. The merchant must implement both request signing and webhook verification per this document. - There are three business headers:
MerchantId,Sign,Timestamp(Unix millisecond timestamp, participates in signing, see Section 4).
3. Key Pair Creation Tutorial
3.1 Generate with OpenSSL (Recommended)
macOS / Linux ships with OpenSSL (or install it), then run:
# 1. Generate the merchant private key (PKCS#8 format, -----BEGIN PRIVATE KEY-----)
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out mch_private.pem
# 2. Export the merchant public key from the private key (X.509/SPKI format, -----BEGIN PUBLIC KEY-----)
openssl pkey -in mch_private.pem -pubout -out mch_public.pemCheck:
openssl pkey -in mch_private.pem -text -noout | head -3 # Should show Private-Key: (2048 bit)Format requirements (important):
The private key must be PKCS#8 (
-----BEGIN PRIVATE KEY-----). The legacy commandopenssl genrsaproduces PKCS#1 (-----BEGIN RSA PRIVATE KEY-----), which the platform does not support. Convert it:bashopenssl pkcs8 -topk8 -nocrypt -in old_private.pem -out mch_private.pemThe public key must be X.509/SPKI (
-----BEGIN PUBLIC KEY-----), notBEGIN RSA PUBLIC KEY.Do not set a passphrase when generating (do not add encryption options such as
-aes256).
3.2 Generate with Java
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048);
KeyPair keyPair = generator.generateKeyPair();
// keyPair.getPrivate().getEncoded() → PKCS#8 DER
// keyPair.getPublic().getEncoded() → X.509/SPKI DER
// Base64-encode and add -----BEGIN/END----- headers to get PEM4. Request Signing
4.1 Signing Rules
- Take the current Unix millisecond timestamp (13-digit numeric string) and put it into the
Timestampheader. - Build the request body JSON string (UTF-8), and sign the exact raw bytes that will be sent.
- Build the content to sign: first concatenate the strings —
Timestamp + ":" + request body(an ASCII colon in between), then take the UTF-8 raw bytes of the concatenated result. - Signature calculation:
Sign = Base64( SHA256withRSA( raw bytes of (Timestamp + ":" + request body), merchant private key ) ).- No key is appended; the timestamp participates in signing and must not be tampered with after signing.
- Put the signature into the
Signheader and send the request body as is. - Sign first, send later; never modify the request body or Timestamp after signing: do not re-serialize the JSON, do not add/remove spaces or newlines, do not reorder fields. Verification matches bytes exactly — any single different byte will fail.
The current platform version validates the presence and numeric format of
Timestamponly; the time window is not checked yet. A time window check (e.g. ±5 minutes) will be enabled later for replay protection, so keep your server clock accurate (NTP sync recommended).
4.2 Request Specification
| Item | Convention |
|---|---|
| Method | POST |
| Content-Type | application/json (UTF-8) |
Header MerchantId | Merchant ID (numeric string) |
Header Timestamp | Unix millisecond timestamp (13-digit numeric string), participates in signing |
Header Sign | Base64 signature calculated per Section 4.1 (344 characters) |
| Request body | Business JSON, field specifications per each country's API documentation |
4.3 Signing Code Example (Java)
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
public class RsaSigner {
/** Private key PEM → PrivateKey */
public static PrivateKey loadPrivateKey(String pem) throws Exception {
String base64 = pem.replace("-----BEGIN PRIVATE KEY-----", "")
.replace("-----END PRIVATE KEY-----", "")
.replaceAll("\\s", "");
byte[] der = Base64.getDecoder().decode(base64);
return KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(der));
}
/** Sign the request: concatenate Timestamp + ":" + body first, then sign the UTF-8 bytes */
public static String sign(String timestamp, String body, PrivateKey privateKey) throws Exception {
String content = timestamp + ":" + body;
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(privateKey);
signature.update(content.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(signature.sign());
}
}Send the request (OkHttp example):
String body = "{\"mchOrderNo\":\"M202611250001\",...}"; // Never modify after building
String timestamp = String.valueOf(System.currentTimeMillis());
String sign = RsaSigner.sign(timestamp, body, privateKey);
Request request = new Request.Builder()
.url("https://platform.example.com/api/payIn")
.post(RequestBody.create(body, MediaType.get("application/json")))
.addHeader("MerchantId", "10001")
.addHeader("Timestamp", timestamp)
.addHeader("Sign", sign)
.build();4.4 Responses and Error Codes
Responses are HTTP 200 + JSON business code:
{ "code": 200, "msg": "SUCCESS", "data": { ... } }Signature-related errors (code=500, check msg):
| msg | Meaning | Troubleshooting |
|---|---|---|
MerchantId_is_null / Sign_is_null | Missing header | Check that the header is present |
Timestamp_is_null / Timestamp_is_error | Missing Timestamp or not numeric | Send a Unix millisecond timestamp (13 digits) |
SIGN_ERROR | RSA verification failed | Is the content to sign the raw bytes of (Timestamp + ":" + the exact body sent)? Does the private key match the public key submitted to the platform? Is Base64 standard encoding? Was the body/Timestamp modified after signing? |
Rsa_key_not_configured | Platform has not configured this merchant's public key | Contact the platform to confirm the public key has been entered |
5. Webhook Verification
When an order status changes, the platform sends a POST webhook to the notifyUrl provided at order creation.
5.1 Webhook Specification
| Item | Convention |
|---|---|
| Method | POST, Content-Type: application/json |
Header MerchantId | Merchant ID |
Header Timestamp | Unix millisecond timestamp (13-digit numeric string), participates in signing |
Header Sign | Platform signature: Base64( SHA256withRSA( raw bytes of (Timestamp + ":" + webhook body), platform private key ) ) |
| Request body | Webhook JSON (fields per each country's webhook documentation) |
The webhook signing rule is identical to request signing: concatenate
Timestamp + ":" + webhook bodyfirst, then sign the UTF-8 raw bytes. Only the keys are swapped: the platform signs with the platform private key, and the merchant verifies with the platform public key.
5.2 Verification Steps
- Read the
Timestampheader and the raw content of the webhook body (reading it as a UTF-8 string is fine; do not deserialize and re-serialize). - Concatenate
Timestamp + ":" + webhook body, take the UTF-8 raw bytes, and verify theSignheader with the platform public key. - Process business logic only after verification passes; reject immediately on failure without any business processing.
- Return HTTP 200 after successful processing. On non-200 the platform retries with increasing intervals (up to about 10 times), so make webhook processing idempotent (deduplicate by merchant order number).
5.3 Verification Code Example (Java)
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class RsaVerifier {
/** Public key PEM → PublicKey */
public static PublicKey loadPublicKey(String pem) throws Exception {
String base64 = pem.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "")
.replaceAll("\\s", "");
byte[] der = Base64.getDecoder().decode(base64);
return KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(der));
}
/** Verify the webhook signature (inputs are Timestamp and the raw body string; concatenation and UTF-8 conversion happen inside) */
public static boolean verify(String timestamp, String body, String signBase64, PublicKey publicKey) {
try {
String content = timestamp + ":" + body;
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initVerify(publicKey);
signature.update(content.getBytes(StandardCharsets.UTF_8));
return signature.verify(Base64.getDecoder().decode(signBase64));
} catch (Exception e) {
return false; // Any malformed signature is treated as verification failure
}
}
}Spring Boot webhook endpoint example:
@PostMapping("/payin/notify")
public ResponseEntity<String> notify(HttpServletRequest request,
@RequestHeader("Sign") String sign,
@RequestHeader("Timestamp") String timestamp) throws IOException {
// Read the raw body string (UTF-8); do not deserialize and re-serialize
String body = new String(request.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
if (!RsaVerifier.verify(timestamp, body, sign, platformPublicKey)) {
return ResponseEntity.status(400).body("SIGN_ERROR");
}
// Verification passed: parse JSON and process business logic (idempotent by mchOrderNo)
return ResponseEntity.ok("SUCCESS");
}6. Key Reminders
- Byte-level consistency is the first principle of RSA signing: both request signing and webhook verification must target the raw bytes. Any re-serialization, space/newline change, or encoding conversion causes
SIGN_ERROR. - The content-to-sign rule is identical for requests and webhooks:
raw bytes of (Timestamp + ":" + message body). Only the key direction differs. - Use UTF-8 everywhere; Base64 must use the standard alphabet (including
+/=), not the URL-Safe variant. - Keep the server clock accurate (NTP sync): although the time window check is not enabled yet, large clock skew will cause requests to be rejected once it is enabled.
7. Online Signing & Verification Tool
The tool below runs entirely in your browser for integration self-testing. The algorithm is SHA256withRSA; when a Timestamp is provided, the content is automatically concatenated as Timestamp + ":" + content, matching the platform's verification rule.
All computations run locally in your browser. Keys and content are never uploaded to any server.