RcbSignatureUtils.java
2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.diligrp.cashier.pipeline.util;
import com.diligrp.cashier.shared.security.HexUtils;
import com.diligrp.cashier.shared.util.ObjectUtils;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
/**
* 安徽农商行的聚合支付文档中并未提到验签功能
*/
public final class RcbSignatureUtils {
public static String sign(Map<String, String> params, String key) {
String data = map2String(params).concat("&key=").concat(key);
MessageDigest md5;
try {
md5 = MessageDigest.getInstance("MD5");
md5.update(data.getBytes(StandardCharsets.UTF_8));
return HexUtils.encodeHexStr(md5.digest(), false);
} catch (NoSuchAlgorithmException ex) {
// Never happened
throw new RuntimeException(ex);
}
}
public static boolean verify(Map<String, String> params, String key, String signature) {
String data = sign(params, key);
return data.equals(signature);
}
public static boolean verify(String params, String key, String signature) {
String data = params.concat("&key=").concat(key);
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
md5.update(data.getBytes(StandardCharsets.UTF_8));
String toBeSigned = HexUtils.encodeHexStr(md5.digest(), false);
return toBeSigned.equals(signature);
} catch (NoSuchAlgorithmException ex) {
// Never happened
throw new RuntimeException(ex);
}
}
public static String map2String(Map<String, String> params) {
TreeMap<String, String> data = new TreeMap<>(Comparator.naturalOrder());
data.putAll(params);
return data.entrySet().stream().filter(e -> ObjectUtils.isNotEmpty(e.getValue()))
.map(e -> e.getKey() + "=" + e.getValue()).collect(Collectors.joining("&", "", ""));
}
}