open-pay-demo/java/SignUtil.java
echo 653a5e4a23 init: multi-language OpenAPI demos (java/php/nodejs/python)
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-20 13:40:28 +08:00

42 lines
1.4 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/** 空值不参与字典序MD5 小写 */
public final class SignUtil {
private SignUtil() {}
public static String buildSign(Map<String, Object> params, String secretKey) throws Exception {
TreeMap<String, Object> sorted = new TreeMap<>();
for (Map.Entry<String, Object> e : params.entrySet()) {
if ("Sign".equals(e.getKey())) {
continue;
}
sorted.put(e.getKey(), e.getValue());
}
List<String> parts = new ArrayList<>();
for (Map.Entry<String, Object> e : sorted.entrySet()) {
Object v = e.getValue();
if (v == null) {
continue;
}
String s = String.valueOf(v);
if (s.isEmpty()) {
continue;
}
parts.add(e.getKey() + "=" + s);
}
String raw = String.join("&", parts) + "&SecretKey=" + secretKey;
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] dig = md.digest(raw.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte b : dig) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
}