Generate signature

Generate signature

The parameter names are sorted according to the order of the ASCII code, converted into a json string, signed with a private key, and HMAC-SHA256 encryption should be used.

Signature generation step description

First step:

Let's assume all the data sent or received to be the set M, and sort the parameters of the non-empty parameter values in the set M according to the parameter name ASCII code from small to large (dictionary order), using the format of the URL key-value pair (ie key1=value1&key2=value2) ...) stitched into a string stringA.

Pay special attention to the following important rules:

  1. The parameter name ASCII code is sorted from small to large (dictionary order);

  2. app_id, timestamp is a required parameter; timestamp is the last five minutes timestamp, which is invalid for more than 5 minutes;

  3. If the value of the parameter is null, it does not participate in the signature;

  4. Parameter names are case sensitive;

  5. The transmitted sign parameter does not participate in the signature, and the generated signature will be checked based on the sign value.

The Second step:

The string is finally stitched to get the stringSignTemp string, and the stringSignTemp is programmed according to HMAC-SHA256, and then all the characters of the obtained string are converted to uppercase, then the signvalue is set.

Pseudo code example

Assume that the parameters transmitted are as follows: channelId: mttest timestamp : 1516320000 body : test

First step: The parameters are sorted according to the key=value format and sorted according to the parameter name ASCII dictionary order as follows:
The second step: splicing the API key:
sign=hash_hmac("sha256",stringSignTemp,key).toUpperCase()="6A9AE1657590FD6257D693A078E1C3E4BB6BA4DC30B23E0EE2496E54170DACD6" //Note: HMAC-SHA256 signature method"

Code example

public void deductBalance() throws IOException {
JTextField field ;
String url = "http://localhost:8088/channel/deductBalance";
TreeMap<String,Object> params = Maps.newTreeMap();
long timestamp = System.currentTimeMillis();
String channelSign = getChannelSign(params, secret);
String result = HttpUtils.sendRequestBody(url, params);
public static String getChannelSign(Map<String, Object> params,String secret) {
StringBuilder result = new StringBuilder();
if (params != null) {
for (Object key : params.keySet()) {
Object value = params.get(key);
String tempString = result + "secret=" + secret;
try {
String sign = EncryptUtils.sha256_HMAC(tempString, secret).toUpperCase();
return sign;
} catch (Exception e) {
return null;

The parameters and order in which the code participates in encryption are:channelId=test91021071617412&orderId=my_test_id&timestamp=1547987604644&secret=my_secret