Skip to content

RSA-based Signature Authentication ​


Differences from MD5 Signing ​

Merchants already integrated with MD5 signing can use the table below to quickly understand the differences:

ItemMD5 SigningRSA2048 Signing
AlgorithmMD5 digest (symmetric key)SHA256withRSA (asymmetric key pair)
KeysapiKey assigned by the platform, shared by both partiesMerchant 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 signRequest body + apiKeyUTF-8 bytes of (Timestamp + ":" + request body), no key appended
Request headersMerchantId, SignMerchantId, Sign, Timestamp (Unix milliseconds, participates in signing)
Signature format32-character hexadecimal stringStandard Base64, 344 characters
Webhook content to signWebhook body + apiKeyUTF-8 bytes of (Timestamp + ":" + webhook body), signed with the platform private key
Webhook headersMerchantId, SignMerchantId, Sign, Timestamp
Verification failure error codeSign_verify_errorSIGN_ERROR

1. Algorithm Overview ​

RSA2048 is a digital signature scheme based on RSA asymmetric cryptography. The parameters are fixed as follows:

ItemConvention
Signature algorithmSHA256withRSA (RSASSA-PKCS1-v1_5, commonly known as RSA2)
Hash algorithmSHA-256
Key length2048 bits
Signature encodingStandard Base64 (256-byte signature → 344 characters, not URL-Safe Base64)

Key direction overview:

ScenarioSigner (holds private key)Verifier (holds public key)
Merchant → Platform API requestMerchant (merchant private key)Platform (merchant public key)
Platform → Merchant order webhookPlatform (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 begin

Notes:

  1. Request signing and webhook verification use the same algorithm: once the platform enables RSA2048 for 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.
  2. There are three business headers: MerchantId, Sign, Timestamp (Unix millisecond timestamp, participates in signing, see Section 4).

3. Key Pair Creation Tutorial ​

macOS / Linux ships with OpenSSL (or install it), then run:

bash
# 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.pem

Check:

bash
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 command openssl genrsa produces PKCS#1 (-----BEGIN RSA PRIVATE KEY-----), which the platform does not support. Convert it:

    bash
    openssl pkcs8 -topk8 -nocrypt -in old_private.pem -out mch_private.pem
  • The public key must be X.509/SPKI (-----BEGIN PUBLIC KEY-----), not BEGIN RSA PUBLIC KEY.

  • Do not set a passphrase when generating (do not add encryption options such as -aes256).

3.2 Generate with Java ​

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 PEM

4. Request Signing ​

4.1 Signing Rules ​

  1. Take the current Unix millisecond timestamp (13-digit numeric string) and put it into the Timestamp header.
  2. Build the request body JSON string (UTF-8), and sign the exact raw bytes that will be sent.
  3. 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.
  4. 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.
  5. Put the signature into the Sign header and send the request body as is.
  6. 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 Timestamp only; 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 ​

ItemConvention
MethodPOST
Content-Typeapplication/json (UTF-8)
Header MerchantIdMerchant ID (numeric string)
Header TimestampUnix millisecond timestamp (13-digit numeric string), participates in signing
Header SignBase64 signature calculated per Section 4.1 (344 characters)
Request bodyBusiness JSON, field specifications per each country's API documentation

4.3 Signing Code Example (Java) ​

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):

java
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:

json
{ "code": 200, "msg": "SUCCESS", "data": { ... } }

Signature-related errors (code=500, check msg):

msgMeaningTroubleshooting
MerchantId_is_null / Sign_is_nullMissing headerCheck that the header is present
Timestamp_is_null / Timestamp_is_errorMissing Timestamp or not numericSend a Unix millisecond timestamp (13 digits)
SIGN_ERRORRSA verification failedIs 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_configuredPlatform has not configured this merchant's public keyContact 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 ​

ItemConvention
MethodPOST, Content-Type: application/json
Header MerchantIdMerchant ID
Header TimestampUnix millisecond timestamp (13-digit numeric string), participates in signing
Header SignPlatform signature: Base64( SHA256withRSA( raw bytes of (Timestamp + ":" + webhook body), platform private key ) )
Request bodyWebhook JSON (fields per each country's webhook documentation)

The webhook signing rule is identical to request signing: concatenate Timestamp + ":" + webhook body first, 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 ​

  1. Read the Timestamp header and the raw content of the webhook body (reading it as a UTF-8 string is fine; do not deserialize and re-serialize).
  2. Concatenate Timestamp + ":" + webhook body, take the UTF-8 raw bytes, and verify the Sign header with the platform public key.
  3. Process business logic only after verification passes; reject immediately on failure without any business processing.
  4. 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) ​

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:

java
@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 ​

  1. 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.
  2. The content-to-sign rule is identical for requests and webhooks: raw bytes of (Timestamp + ":" + message body). Only the key direction differs.
  3. Use UTF-8 everywhere; Base64 must use the standard alphabet (including + / =), not the URL-Safe variant.
  4. 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.

Online Sign

Online Verify

Released under the MIT License.