Skip to main content

Signature and Verification

Generate request signature​

Before generate signature, please make sure the following materials are ready:

  • Get your Merchant Safecode
  • Generate a RSA key pair. Your can generate it via our service or by yourself
  • Upload your RSA public key to our service

Please follow this guideline to generate your request signature:

  1. Sort request parameters by key in ASCII order
  2. Concat each parameters' key value by = and join all parameters by &, then append & and your safecode at suffix of sign string
  3. Encrypt sign string in SHA256 by your RSA private key
  4. Encode encrypted string in base64 to get your final signature
// Concatenated string before sign
amount=1&channel=alipay&currency=CNY&merchantid=123456&mid=1&notifyurl=www.abc.com/callback&returnurl=www.abc.com/returnurl&service=Payment&PUT_YOUR_SAFECODE_HERE
import java.io.*;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;

public String generateSignature(Map params, String safecode, List<String> ignoreFields) {

SortedSet<String> sortedParams = new TreeSet<>(params.keySet());
String concatStr = "";
for (String key: sortedParams) {
if (ignoreFields.contains(key)) continue;
concatStr += String.format("%s=%s&", key, params.get(key));
}
concatStr += safecode;

try {
String strKey = Files
.readString(Path.of('your_priavte_key.pem'))
.replaceAll("(-----BEGIN PRIVATE KEY-----|-----END PRIVATE KEY-----|\n)", "");
byte [] binKey = Base64.getDecoder().decode(strKey);
PKCS8EncodedKeySpec pkcs8Key = new PKCS8EncodedKeySpec(binKey);
PrivateKey priKey = KeyFactory.getInstance("RSA").generatePrivate(pkcs8Key);

Signature rsa = Signature.getInstance("SHA256withRSA");
rsa.initSign(priKey);
rsa.update(concatStr.getBytes("UTF-8"));
return Base64.getEncoder().encodeToString(rsa.sign());
} catch (Exception e) {
return null;
}
}

Verify PTS response signature​

Before verify signature, please make sure the following materials are ready:

  • Get your Merchant Safecode
  • Get RSA public key of PTS platform

Please follow this guideline to verification signature sent from PTS:

  1. Sort response parameters except signature by key in ASCII order. All parameters except signature should participate in the verification string
  2. Concat key/value of parameters by = symbol, then join all parameters by & symbol
  3. Append & and your merchant safecode at suffix of the verification string
  4. Decode response signature by base64 decoder to binary signature
  5. Verify the binary signature via SHA256 with verification string and PTS platform public key
import base64
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15

def verifySignature(sign, verifyStr, pubKey):
pubKey = RSA.import_key(pubKey)
hash = SHA256.new(verifyStr.encode('utf-8'))
binarySign = base64.b64decode(sign)

try:
pkcs1_15.new(pubKey).verify(hash, binarySign)
return True
except (ValueError, TypeError):
return False