package com.stylefeng.guns.modular.system.util; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.util.Base64; /** * 签名工具 * * @author Lux * @version 1.0.0 * @since 2026/6/5 11:20 */ public class SignUtil { private static final String HMAC_SHA256 = "HmacSHA256"; /** * 数据上报生成签名 * * @param method 请求方式 * @param url 请求路基,api的路径 * @param accessKey 身份标识 * @param accessSecret 密钥 * @param timestamp 时间戳,精确到秒 * @param nonce 唯一随机数,6位随机数 * @return 签名后的数据 */ public static String generateSign(String method, String url, String accessKey, String accessSecret, String timestamp, String nonce) { try { String data = String.format("%s&%s&%s&%s&%s", method.toUpperCase(), url, accessKey, timestamp, nonce); Mac mac = Mac.getInstance(HMAC_SHA256); SecretKeySpec secretKeySpec = new SecretKeySpec(accessSecret.getBytes(StandardCharsets.UTF_8), HMAC_SHA256); mac.init(secretKeySpec); byte[] signBytes = mac.doFinal(data.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(signBytes); } catch (Exception e) { throw new RuntimeException("生成签名失败", e); } } }