All The Request Require Timestamp And Sign

The specific steps to generate a signature are as follows:

Arrange the request parameters in ascending order according to the dictionary order of parameter names.
Splicing the sorted parameters into a string in the format: key 1 = value1 & key 2 = value2 & ... & keyn = valuen.
The spliced string is encrypted by HMAC-SHA256, and the SecretKey is used as the encryption key.
Convert the encrypted result into a hexadecimal string, which is the generated signature.

Sign demo to initiate API

public class HmacUtil {

    private final static Charset UTF8 = StandardCharsets.UTF_8;

    public static String hmac256(String key, String msg) throws Exception {
        // Get Mac instance and specify HmacSHA256 algorithm.
        Mac mac = Mac.getInstance("HmacSHA256");
        // Create a SecretKeySpec instance to store key information. The mac.getAlgorithm () method gets the name of the algorithm used by the Mac instance.
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(UTF8), mac.getAlgorithm());
        // Key initialization.
        mac.init(secretKeySpec);
        // Calculate the HmacSHA256 digest value of the message.
        byte[] data = mac.doFinal(msg.getBytes(UTF8));
        // Converts a summary value to a hexadecimal string
        String hmac256Sign = DatatypeConverter.printHexBinary(data).toLowerCase();
        log.info("HmacSHA256 rawContent is [{}], key is [{}], hash result is [{}]", msg, key, hmac256Sign);
        return hmac256Sign;
    }

  

    public static String getStringToSign(Map<String, Object> params) {
        TreeMap<String, Object> treeMap = new TreeMap<>(params);
        StringBuilder s2s = new StringBuilder();
        for (String k : treeMap.keySet()) {
            if(StringUtils.hasText(k)){
                Object value = params.get(k);
                if(value instanceof Map){
                    continue;
                }else if(value instanceof List){
                    continue;
                }
                if (Objects.nonNull(value) && StrUtil.isNotEmpty(value.toString())) {
                    s2s.append(k).append("=").append(params.get(k).toString()).append("&");
                }
            }
        }
        return s2s.substring(0, s2s.length() - 1);
    }

    public static void main(String[] args) throws Exception {

        final String appid = "aaa";
        final String secretKey = "bbb";

        Map<String, Object> map = new HashMap<>();
        // The actual call needs to update the parameters. This is only an example to demonstrate that the signature verification passed.
        map.put("orderId", "1400006666");
        map.put("network", "TRX");
        map.put("amount", "1234");
        map.put("cryptoCurrency","USDT");
        map.put("fiat", "USD");
        map.put("type", "ONE");
        map.put("timestamp", String.valueOf(System.currentTimeMillis()));
        map.put("appid", appid);

        String sign = getStringToSign(map);
        log.info("sign is {}", sign);

        String hmac256Sign = hmac256(secretKey, sign);
        log.info("hmac256Sign is {}", hmac256Sign);

    }

}

const crypto = require('crypto');

class HmacUtil {
  static hmac256(key, msg) {
    const mac = crypto.createHmac('sha256', key);
    const data = mac.update(msg).digest('hex').toLowerCase();
    console.log(`HmacSHA256 rawContent is [${msg}], key is [${key}], hash result is [${data}]`);
    return data;
  }

  static getStringToSign(params) {
    const treeMap = new Map(Object.entries(params).sort());
    let s2s = '';

    for (const [k, v] of treeMap) {
      if (!k || typeof v === 'object') {
        continue;
      }
      if (v !== null && v !== undefined && String(v)) {
        s2s += `${k}=${v}&`;
      }
    }

    return s2s.slice(0, -1);
  }
}

const appid = 'aaa';
const secretKey = 'bbb';
// The actual call needs to update the parameters. This is only an example to demonstrate that the signature verification passed.
const map = {
  orderId: '1400006666',
  network: 'TRX',
  amount: '1234',
  cryptoCurrency: 'USDT',
  fiat: 'USD',
  type: 'ONE',
  timestamp: String(Date.now()),
  appid: appid,
};

const sign = HmacUtil.getStringToSign(map);
console.log(`sign is ${sign}`);

const hmac256Sign = HmacUtil.hmac256(secretKey, sign);
console.log(`hmac256Sign is ${hmac256Sign}`);

import hashlib
import hmac
from typing import Dict

class HmacUtil:
    @staticmethod
    def hmac256(key: str, msg: str) -> str:
       
        data = hmac.new(key.encode(), msg.encode(), hashlib.sha256).digest()
       
        hmac256Sign = data.hex().lower()
        print(f"HmacSHA256 rawContent is [{msg}], key is [{key}], hash result is [{hmac256Sign}]")
        return hmac256Sign

    @staticmethod
    def get_string_to_sign(params: Dict[str, object]) -> str:
     
        s2s = '&'.join([f"{k}={v}" for k, v in sorted(params.items()) if v is not None and str(v)])
        return s2s

if __name__ == '__main__':
    appid = "aaa"
    secretKey = "bbb"
    ##The actual call needs to update the parameters. This is only an example to demonstrate that the signature verification passed.
    params = {
        "orderId": "1400006666",
        "network": "TRX",
        "amount": "1234",
        "cryptoCurrency": "USDT",
        "fiat": "USD",
        "type": "ONE",
        "timestamp": str(int(time.time() * 1000)),
        "appid": appid
    }

    sign = HmacUtil.get_string_to_sign(params)
    print(f"sign is {sign}")

    hmac256Sign = HmacUtil.hmac256(secretKey, sign)
    print(f"hmac256Sign is {hmac256Sign}")

<?php

class HmacUtil {
  public static function hmac256($key, $msg) {
  
    $data = hash_hmac('sha256', $msg, $key, true);
   
    $hmac256Sign = bin2hex($data);
    echo "HmacSHA256 rawContent is [{$msg}], key is [{$key}], hash result is [{$hmac256Sign}]\n";
    return $hmac256Sign;
  }

  public static function getStringToSign($params) {
   
    ksort($params);
    $s2s = '';
    foreach ($params as $k => $v) {
      if (is_array($v)) {
        continue;
      } else if (!empty($v)) {
        $s2s .= "{$k}={$v}&";
      }
    }
    return rtrim($s2s, '&');
  }
}

$appid = 'aaa';
$secretKey = 'bbb';
// The actual call needs to update the parameters. This is only an example to demonstrate that the signature verification passed.
$params = array(
  'orderId' => '1400006666',
  'network' => 'TRX',
  'amount' => '1234',
  'cryptoCurrency' => 'USDT',
  'fiat' => 'USD',
  'type' => 'ONE',
  'timestamp' => strval(time() * 1000),
  'appid' => $appid,
);

$sign = HmacUtil::getStringToSign($params);
echo "sign is {$sign}\n";

$hmac256Sign = HmacUtil::hmac256($secretKey, $sign);
echo "hmac256Sign is {$hmac256Sign}\n";

?>

package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"sort"
	"strings"
	"time"
)

func hmac256(key string, msg string) string {
	
	h := hmac.New(sha256.New, []byte(key))
	h.Write([]byte(msg))
	data := h.Sum(nil)

	hmac256Sign := hex.EncodeToString(data)
	fmt.Printf("HmacSHA256 rawContent is [%s], key is [%s], hash result is [%s]\n", msg, key, hmac256Sign)
	return hmac256Sign
}

func getStringToSign(params map[string]interface{}) string {
	
	keys := make([]string, 0, len(params))
	for k := range params {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	var s2s strings.Builder
	for _, k := range keys {
		if v, ok := params[k]; ok {
			switch t := v.(type) {
			case map[string]interface{}:
				continue
			case []interface{}:
				continue
			default:
				if str, ok := v.(string); ok && str != "" {
					s2s.WriteString(fmt.Sprintf("%s=%v&", k, v))
				}
			}
		}
	}
	return s2s.String()[:s2s.Len()-1]
}

func main() {
	appid := "aaa"
	secretKey := "bbb"
  // The actual call needs to update the parameters. This is only an example to demonstrate that the signature verification passed.
	params := map[string]interface{}{
		"orderId":        "1400006666",
		"network":        "TRX",
		"amount":         "1234",
		"cryptoCurrency": "USDT",
		"fiat":           "USD",
		"type":           "ONE",
		"timestamp":      fmt.Sprintf("%d", time.Now().UnixNano()/int64(time.Millisecond)),
		"appid":          appid,
	}

	sign := getStringToSign(params)
	fmt.Printf("sign is %s\n", sign)

	hmac256Sign := hmac256(secretKey, sign)
	fmt.Printf("hmac256Sign is %s\n", hmac256Sign)
}

import 'dart:convert';
import 'package:crypto/crypto.dart';

class HmacUtil {
  static String hmac256(String key, String msg) {
   
    var hmac = Hmac(sha256, utf8.encode(key));
    var data = hmac.convert(utf8.encode(msg)).bytes;
   
    var hmac256Sign = hex.encode(data).toLowerCase();
    print('HmacSHA256 rawContent is [$msg], key is [$key], hash result is [$hmac256Sign]');
    return hmac256Sign;
  }

  static String getStringToSign(Map<String, dynamic> params) {
   
    var keys = params.keys.toList()..sort();
    var s2s = StringBuffer();
    for (var k in keys) {
      if (params[k] is Map || params[k] is List) {
        continue;
      } else if (params[k] != null && params[k].toString().isNotEmpty) {
        s2s.write('$k=${params[k]}&');
      }
    }
    return s2s.toString().substring(0, s2s.length - 1);
  }
}

void main() {
  final appid = 'aaa';
  final secretKey = 'bbb';
  // The actual call needs to update the parameters. This is only an example to demonstrate that the signature verification passed.
  var map = <String, dynamic>{
    'orderId': '1400006666',
    'network': 'TRX',
    'amount': '1234',
    'cryptoCurrency': 'USDT',
    'fiat': 'USD',
    'type': 'ONE',
    'timestamp': '${DateTime.now().millisecondsSinceEpoch}',
    'appid': appid,
  };

  var sign = HmacUtil.getStringToSign(map);
  print('sign is $sign');

  var hmac256Sign = HmacUtil.hmac256(secretKey, sign);
  print('hmac256Sign is $hmac256Sign');
}