签名计算过程(Java 版本)
<p>import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;</p>
<p>public class HmacSha256Util {
public static String generateSignature(String merchantId, String userName, String timestamp, String apiKey) {
try {
// 参数校验
if (merchantId == null || userName == null || timestamp == null || apiKey == null) {
throw new IllegalArgumentException("Parameters cannot be null");
}</p>
<pre><code> // 拼接数据
String rawData = merchantId + userName + timestamp;
// 初始化 HMAC-SHA256
Mac hmacSHA256 = Mac.getInstance(&quot;HmacSHA256&quot;);
SecretKeySpec secretKey = new SecretKeySpec(apiKey.getBytes(StandardCharsets.UTF_8), &quot;HmacSHA256&quot;);
hmacSHA256.init(secretKey);
// 计算哈希
byte[] hash = hmacSHA256.doFinal(rawData.getBytes(StandardCharsets.UTF_8));
// 转换为十六进制字符串
return bytesToHex(hash);
} catch (Exception e) {
throw new RuntimeException(&quot;Failed to generate HMAC-SHA256 signature&quot;, e);
}
}
private static String bytesToHex(byte[] bytes) {
StringBuilder hexString = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
hexString.append(String.format(&quot;%02x&quot;, b));
}
return hexString.toString();
}
public static void main(String[] args) {
// 示例
String merchantId = &quot;123456&quot;;
String userName = &quot;testUser&quot;;
String timestamp = &quot;1700000000&quot;;
String apiKey = &quot;mySecretKey&quot;;
String signature = generateSignature(merchantId, userName, timestamp, apiKey);
System.out.println(&quot;Generated Signature: &quot; + signature);
}</code></pre>
<p>}</p>