加签/验签工具类SignUtil
作者:互联网
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.codec.digest.DigestUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
/**
*
* 加签/验签工具类
*
* @author qsh
* @date 2018/12/19 上午11:18
*
*/
@Slf4j
public class SignUtil {
/**
* 加签方法
* @param bean Javabean对象
* @param key 加签盐值
* @return
*/
public static String sign(Object bean, String key){
return sign(beanToMap(bean), key);
}
/**
* 加签方法
* @param map Map对象
* @param key 加签盐值
* @return
*/
public static String sign(Map<String, Object> map, String key){
String genSign = "";
try {
//默认将按照key值进行升序排序
TreeMap treeMap = sortMap(map);
//原始签文
String orgStr = JSON.toJSONString(treeMap).concat(key);
log.info("加签原文:"+orgStr);
//指定编码格式
genSign = DigestUtils.md5Hex(orgStr.getBytes("UTF-8"));
log.info("加签密文:"+genSign);
}catch (Exception e){
log.info("加签失败",e);
}
return genSign;
}
/**
* 验签方法
* @param bean Javabean对象
* @param key 验签盐值
* @param sign 签名密文
* @return
*/
public static boolean verify(Object bean, String key, String sign){
boolean flag = false;
try{
Map paramsMap = beanToMap(bean);
//默认将按照key值进行升序排序
TreeMap treeMap = sortMap(paramsMap);
//原始签文
String orgStr = JSON.toJSONString(treeMap).concat(key);
log.info("验签原文:"+orgStr);
//指定编码格式
String genSign = DigestUtils.md5Hex(orgStr.getBytes("UTF-8"));
log.info("验签密文:"+genSign);
if(genSign.equals(sign)){
flag = true;
}
}catch (Exception e){
log.info("验签失败",e);
}
return flag;
}
/**
* 将JavaBean对象转化为Map
* @param bean
* @return
*/
public static Map beanToMap(Object bean){
Map returnMap = new HashMap();
try {
Class type = bean.getClass();
BeanInfo beanInfo = Introspector.getBeanInfo(type);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
//循环获取bean属性和值放入map中
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
//忽略sign属性
if (!"sign".equals(propertyName)&&!"class".equals(propertyName)) {
Method readMethod = descriptor.getReadMethod();
Object result = readMethod.invoke(bean, new Object[0]);
returnMap.put(propertyName, result);
}
}
}catch (Exception e){
log.info("beanToMap失败",e);
}
return returnMap;
}
/**
* map排序
*
* @param map
* @return
*/
private static TreeMap sortMap(Map<String, Object> map) {
TreeMap treeMap = new TreeMap();
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getValue() instanceof Map) {
TreeMap subTreeMap = sortMap((Map) entry.getValue());
treeMap.put(entry.getKey(), subTreeMap);
} else {
treeMap.put(entry.getKey(), entry.getValue());
}
}
return treeMap;
}
}
标签:Map,return,String,bean,key,SignUtil,验签,import,加签 来源: https://blog.csdn.net/qishao1101/article/details/118395015