Notification签名代码示例
Java
static void notificationSignTest() throws Exception {
/*
请求头
x-lf-notification-version:"1.0",
x-lf-algo:"HMAC-SHA1",
x-lf-timestamp:"12345648444",
x-lf-signature:"Ou8a5lyzPjN86ikmLeFC/pnWR3hcrEXQWV8S+RY0DMjEN9ec="
*/
//请求签名
String requestSign = "Ou8a5lyzPjN86ikmLeFC/pnWR3hcrEXQWV8S+RY0DMjEN9ec=";
//请求体
String body = "{\"name\": \"liguoli\",\"age\": 18}";
//请求头(mock)
Map<String, String> map = new HashMap<>();
map.put("x-lf-notification-version", "1.0");
map.put("x-lf-algo", "HMAC-SHA1");
map.put("x-lf-timestamp", "12345648444");
map.put("x-lf-signature", "Ou8a5lyzPjN86ikmLeFC/pnWR3hcrEXQWV8S+RY0DMjEN9ec=");
//字典排序 使用springboot自带jackson可选其余方法,进行字典排序,该处省略
ObjectMapper objectMapper = new ObjectMapper();
Map sortMap = objectMapper.readValue(body, Map.class);
objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
String mapText = objectMapper.writeValueAsString(sortMap);
//组织报文
String text = map.get("x-lf-notification-version") + ":" + map.get("x-lf-algo") + ":" + map.get("x-lf-timestamp") + mapText;
//秘钥id
String keyId = "Ou8a5lyzPjN86ikmLeFC";
//秘钥值(通过查询获取)
String keyValue = "3QY0I6jA6jOfeIQbOde3CG2DeOllV1zufpFR393my78h3tCn7P1IfyUIhV3cS8ks";
//HmacSHA1算法
SecretKeySpec signKey = new SecretKeySpec(keyValue.getBytes(), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
//用给定密钥初始化Mac对象
mac.init(signKey);
//完成操作
byte[] hmac = mac.doFinal(text.getBytes());
//转换base64字符串
String signature = keyId + "/" + Base64.getEncoder().encodeToString(hmac);
System.out.println(signature);
//是否相同
System.out.println(signature.equals(requestSign));
}
修改于 2025-03-21 08:29:33