package demo;import java.util.Arrays;
import java.util.Map;import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.codec.digest.DigestUtils;/*** 加密生成签名*/
public class Encrypt {public static void main(String[] args) {/**签名加密*/Map<String, String> map = Maps.newHashMap();map.put("name", "xiaoHong");map.put("age", "18");/**调用生成签名方法,将组装好的map集合和密钥传入*/String sign = genSign(map, "123456");System.out.println("生成签名密钥:" + sign);//生成签名密钥:18D35F3F3D95173302930EC3ADC2DEC5}/*** 生成签名** @param map 参数* @param signKey 签名密钥* @return*/public static String genSign(final Map<String, String> map, String signKey) {/*创建一个长度和map.size()大小一致的字符串数组*/String[] keyArray = new String[map.keySet().size()];/*将map的keySet集合转化为数组*/map.keySet().toArray(keyArray);/*将数组元素按字典进行排序*/Arrays.sort(keyArray);StringBuffer stringBuffer = new StringBuffer();/*遍历数组*/for (String key : keyArray) {/*将键和值按照key=value&进行拼接*/if (StringUtils.isNotBlank(key) && StringUtils.isNotBlank(map.get(key))) {stringBuffer.append(key).append("=").append(map.get(key)).append("&");}}/*拼接密钥时先将密钥做一次md5加密,后拼接*/stringBuffer.append("key=").append(DigestUtils.md5Hex(signKey));/*将拼接的字符串进行md5加密后转为大写*/String sign = DigestUtils.md5Hex(stringBuffer.toString()).toUpperCase();return sign;}
}
引用包:
<dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.8.1</version></dependency><dependency><groupId>commons-codec</groupId><artifactId>commons-codec</artifactId><version>1.15</version></dependency><dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>30.0-jre</version></dependency>