欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot自定义注解API数据加密和签名校验

程序员文章站 2022-04-03 18:31:46
api数据数据签名(md5,sha1)签名枚举类sginenum.javapackage com.jx.app.api.framework.annotation.enums;/** * @class...

api数据数据签名(md5,sha1)

签名枚举类sginenum.java

package com.jx.app.api.framework.annotation.enums;

/**  
* @classname: sginenum  
* @description: todo(这是一个签名枚举类)  
* @author gangyu
* @date 2018年11月20日 下午4:30:44  
*/
public enum sginenum {
 //0不需要签名,1使用md5数据加密 2 使用sha数据加密
 any(0), md5(1), sha1(2);
 private final int value;

 private sginenum(int value) {
  this.value = value;
 }

 public int getvalue() {
  return value;
 }
}

签名注解类sginanot.java

/**    
* @title: sginanot.java  
* @package com.jxkj.app.api.framework  
* @description: todo(用一句话描述该文件做什么)  
* @author gangyu
* @date 2018年11月20日 下午4:07:58  
* @version v1.0    
*/
package com.jx.app.api.framework.annotation;

import java.lang.annotation.elementtype;
import java.lang.annotation.retention;
import java.lang.annotation.retentionpolicy;
import java.lang.annotation.target;

import com.jx.app.api.framework.annotation.enums.sginenum;

/**  
* @classname: sginanot  
* @description: todo(签名验证注解)  
* @author gangyu
* @date 2018年11月20日 下午4:07:58  
*    
*/
@target({elementtype.method})
@retention(retentionpolicy.runtime)
public @interface sginanot {
 sginenum type() default sginenum.any;//默认不需要签名
}

加密工具类md5.java

package com.jx.common.entrypt;

import java.io.unsupportedencodingexception;
import java.math.biginteger;
import java.security.messagedigest;
import java.security.nosuchalgorithmexception;
import java.util.hashmap;
import java.util.map;

import org.apache.commons.lang3.stringutils;
import org.slf4j.logger;
import org.slf4j.loggerfactory;

import com.jx.common.utils.beanutil;
import com.jx.common.utils.testentity;

/**
 * @classname: md5
 * @description: todo(md5加密工具)
 * @author gangyu
 * @date 2018年11月20日 下午2:12:14
 *
 */
public class md5 {


 private static final logger log = loggerfactory.getlogger(md5.class);

 public static string private_key = "这是你的密钥";
 
    private static final string hexdigits[] = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};

 public static string encrypt(string plaintext) {
  try {
   return encrypt(plaintext,true);
  } catch (unsupportedencodingexception e) {
   e.printstacktrace();
   log.error("md5加密异常:",e);
   return null;
  }
 }
 
 /**
  * @title: encrypt
  * @description: todo(16位或32位密码)
  * @param @param
  *            plaintext
  * @param @param
  *            flag true为32位,false为16位
  * @throws unsupportedencodingexception
  */
 public static string encrypt(string plaintext, boolean flag) throws unsupportedencodingexception {
  try {
   if (stringutils.isempty(plaintext)) {
    return null;
   }
   messagedigest md = messagedigest.getinstance("md5");
            string encrstr = bytearraytohexstring(md.digest(plaintext.getbytes("utf-8")));
   if (flag)
    return encrstr;
   else
    return encrstr.substring(8, 24);
  } catch (nosuchalgorithmexception e) {
   e.printstacktrace();
   return null;
  }

 }

 @suppresswarnings("unchecked")
 public static string encrypt(object obj){
  if(obj==null){
   return null;
  }
  map<string, object> map = new hashmap<string,object>();
  if(obj instanceof map){
   map=(map<string, object>) obj;
  }else{
   map = beanutil.transbean2map(obj);
  }
  return encrypt(map,true);
 }
 
 /**
  * @title: encrypt
  * @description: todo(16位或32位密码)
  * @param @param
  *            plaintext
  * @param @param
  *            flag true为32位,false为16位
  * @throws unsupportedencodingexception
  */
 public static string encrypt(map<string, object> map, boolean flag) {
  string param = null;
  map.remove("sign");
  map.remove("encrypt");
  string result = beanutil.maporderstr(map);
  if (stringutils.isempty(result)) {
   return null;
  }
  param = encrypt(encrypt(result)+private_key);
  if (flag) {
   return param;
  } else {
   param = param.substring(8, 24);
  }
  return param;
 }

 public static map<string, object> resultmap = new hashmap<string, object>();
 @suppresswarnings("unchecked")
 public static map<string, object> mapfn(map<string, object> map) {
  for (string key : map.keyset()) {
   if (map.get(key) != null && map.get(key) != "" && (!key.equals("btype") && !key.equals("sign"))) {
    if (key.equals("input")) {
     if (map.get(key) != null) {
      mapfn((map<string, object>) map.get(key));
     }
    } else {
     resultmap.put(key, map.get(key));
    }
   }
  }
  return resultmap;
 }
 
 @suppresswarnings("unchecked")
 public static boolean check(object obj){
  map<string,object> map=new hashmap<string,object>();
  if(obj==null){
   return false;
  }
  if(obj instanceof map){
   map=(map<string, object>) obj;
  }else{
   map = beanutil.transbean2map(obj);
  }
  string sign=(string)map.get("sign");
  if(sign==null){
   return false;
  }
  string str=encrypt(obj);
  return sign.equals(str)?true:false;
 }

    public static string bytearraytohexstring(byte b[]){
        stringbuffer resultsb = new stringbuffer();
        for(int i = 0; i < b.length; i++){
            resultsb.append(bytetohexstring(b[i]));
        }
        return resultsb.tostring();
    }

    public static string bytetohexstring(byte b){
        int n = b;
        if(n < 0){
            n += 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexdigits[d1] + hexdigits[d2];
    }
    
 public static void main(string[] args) throws unsupportedencodingexception {
  testentity test = new testentity();
  test.setid("1");
  test.setage("20");
  test.setclaes("你好");
  test.setname("gyu");
  test.setcreatetime("2018-11-20");
  test.setsign("5189bd815c3850395f30779d0e59229e");
  system.out.println("md5验签成功:"+check(test));
 }

}

sha加密工具类sha1.java

package com.jx.common.entrypt;

import java.io.unsupportedencodingexception;
import java.security.messagedigest;
import java.security.nosuchalgorithmexception;
import java.util.hashmap;
import java.util.map;

import org.apache.commons.lang3.stringutils;
import org.slf4j.logger;
import org.slf4j.loggerfactory;

import com.jx.common.utils.beanutil;

/**  
* @classname: sha1util  
* @description: todo(sha加密)  
* @author gangyu
* @date 2018年11月20日 下午2:08:36  
*    
*/
public class sha1 {
 private static final logger log = loggerfactory.getlogger(sha1.class);
 public static string encrypt(string str){
     if (null == str || 0 == str.length()){
         return null;
     }
     char[] hexdigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 
             'a', 'b', 'c', 'd', 'e', 'f'};
     try {
         messagedigest mdtemp = messagedigest.getinstance("sha1");
         mdtemp.update(new string(str.getbytes("iso8859-1"), "utf-8").getbytes());
         byte[] md = mdtemp.digest();
         int j = md.length;
         char[] buf = new char[j * 2];
         int k = 0;
         for (int i = 0; i < j; i++) {
             byte byte0 = md[i];
             buf[k++] = hexdigits[byte0 >>> 4 & 0xf];
             buf[k++] = hexdigits[byte0 & 0xf];
         }
         return new string(buf);
     } catch (nosuchalgorithmexception e) {
         e.printstacktrace();
   log.error("sha1加密异常:",e);
     } catch (unsupportedencodingexception e) {
         e.printstacktrace();
   log.error("sha1加密异常:",e);
     }
  return str;
 }
 
 @suppresswarnings("unchecked")
 public static string encrypt(object obj) {
  if(obj==null){
   return null;
  }
  map<string, object> map = new hashmap<string,object>();
  if(obj instanceof map){
   map=(map<string, object>) obj;
  }else{
   map = beanutil.transbean2map(obj);
  }
  map.remove("sign");
  map.remove("encrypt");
  string result = beanutil.maporderstr(map);
  if (stringutils.isempty(result)) {
   return null;
  }
  return encrypt(result);
 }
 
 @suppresswarnings("unchecked")
 public static boolean check(object obj){
  map<string,object> map=new hashmap<string,object>();
  if(obj==null){
   return false;
  }
  if(obj instanceof map){
   map=(map<string, object>) obj;
  }else{
   map = beanutil.transbean2map(obj);
  }
  string sign=(string)map.get("sign");
  if(sign==null){
   return false;
  }
  string str=encrypt(obj);
  return sign.equals(str)?true:false;
 
 }
}

返回数据对称加密des.java

package com.jx.common.entrypt;

import java.security.key;
import java.util.map;

import javax.crypto.cipher;
import javax.crypto.secretkeyfactory;
import javax.crypto.spec.desedekeyspec;
import javax.crypto.spec.ivparameterspec;

import com.google.gson.gson;
import com.jx.common.utils.base64;


/**
* @classname: des  
* @description: todo(对称加密工具)  
* @author gangyu
* @date 2018年11月20日 下午1:18:49  
*/
public class des {
 // 密钥
 private final static string secretkey = "123456789987654321";
 // 向量
 private final static string iv = "ggboy123";
 // 加解密统一使用的编码方式
 private final static string encoding = "utf-8";

 /**
 * @title: encode
 * @description: todo(加密)
 * @param string
 * @author gangyu2
 * @date 2018年11月20日下午1:19:19
  */
 public static string encode(string plaintext){
  key deskey = null;
  desedekeyspec spec;
  try {
   spec = new desedekeyspec(secretkey.getbytes());
   secretkeyfactory keyfactory = secretkeyfactory.getinstance("desede");
   deskey = keyfactory.generatesecret(spec);

   cipher cipher = cipher.getinstance("desede/cbc/pkcs5padding");
   ivparameterspec ips = new ivparameterspec(iv.getbytes());
   cipher.init(cipher.encrypt_mode, deskey, ips);
   byte[] encryptdata = cipher.dofinal(plaintext.getbytes(encoding));
   return base64.encode(encryptdata);
  } catch (exception e) {
   e.printstacktrace();
   return "";
  }
 }

 /**
 * @title: decode
 * @description: todo(解密)
 * @param string
 * @author gangyu2
 * @date 2018年11月20日下午1:19:37
  */
 public static string decode(string encrypttext){
  try{

   key deskey = null;
   desedekeyspec spec = new desedekeyspec(secretkey.getbytes());
   secretkeyfactory keyfactory = secretkeyfactory.getinstance("desede");
   deskey = keyfactory.generatesecret(spec);
   cipher cipher = cipher.getinstance("desede/cbc/pkcs5padding");
   ivparameterspec ips = new ivparameterspec(iv.getbytes());
   cipher.init(cipher.decrypt_mode, deskey, ips);

   byte[] decryptdata = cipher.dofinal(base64.decode(encrypttext));

   return new string(decryptdata, encoding);
  }catch(exception e){
   e.printstacktrace();
   return "";
  }
 }
}

beanutil.java

package com.jx.common.utils;

import java.beans.beaninfo;
import java.beans.introspector;
import java.beans.propertydescriptor;
import java.lang.reflect.field;
import java.lang.reflect.method;
import java.util.arraylist;
import java.util.collections;
import java.util.comparator;
import java.util.hashmap;
import java.util.list;
import java.util.map;
import java.util.map.entry;

import org.apache.commons.beanutils.beanutils;
import org.apache.commons.beanutils.propertyutilsbean;
import org.apache.commons.lang3.stringutils;

public class beanutil {

 // map --> bean 2: 利用org.apache.commons.beanutils 工具类实现 map --> bean
 public static void transmap2bean2(map<string, object> map, object obj) {
  if (map == null || obj == null) {
   return;
  }
  try {
   beanutils.populate(obj, map);
  } catch (exception e) {
   system.out.println("transmap2bean2 error " + e);
  }
 }

 // map --> bean 1: 利用introspector,propertydescriptor实现 map --> bean
 public static void transmap2bean(map<string, object> map, object obj) {
  try {
   beaninfo beaninfo = introspector.getbeaninfo(obj.getclass());
   propertydescriptor[] propertydescriptors = beaninfo
     .getpropertydescriptors();

   for (propertydescriptor property : propertydescriptors) {
    string key = property.getname();

    if (map.containskey(key)) {
     object value = map.get(key);
     // 得到property对应的setter方法
     method setter = property.getwritemethod();
     setter.invoke(obj, value);
    }

   }

  } catch (exception e) {
   system.out.println("transmap2bean error " + e);
  }

  return;

 }

 // bean --> map 1: 利用introspector和propertydescriptor 将bean --> map
 public static map<string, object> transbean2map(object obj) {
  if (obj == null) {
   return null;
  }
  map<string, object> map = new hashmap<string, object>();
  try {
   beaninfo beaninfo = introspector.getbeaninfo(obj.getclass());
   propertydescriptor[] propertydescriptors = beaninfo.getpropertydescriptors();
   for (propertydescriptor property : propertydescriptors) {
    string key = property.getname();

    // 过滤class属性
    if (!key.equals("class")) {
     // 得到property对应的getter方法
     method getter = property.getreadmethod();
     object value = getter.invoke(obj);
     if(null !=value && !"".equals(value))
      map.put(key, value);
    }

   }
  } catch (exception e) {
   system.out.println("transbean2map error " + e);
  }
  return map;

 }
 
 public static string maporderstr(map<string, object> map) {
  list<map.entry<string, object>> list = new arraylist<map.entry<string, object>>(map.entryset());
  collections.sort(list, new comparator<map.entry<string, object>>() {
   public int compare(entry<string, object> o1, entry<string, object> o2) {
    return o1.getkey().compareto(o2.getkey());
   }
  });

  stringbuilder sb = new stringbuilder();
  for (map.entry<string, object> mapping : list) {
   sb.append(mapping.getkey() + "=" + mapping.getvalue() + "&");
  }
  return sb.substring(0, sb.length() - 1);
 }
 
 

 /**
  * 
  * 将源的属性复制到目标属性上去
  * @param src
  * @param dest
  * @lastmodified
  * @history
  */
 public static void copyproperties(object dest,object src) {
  if (src == null || dest == null) {
   return;
  }
  // 获取所有的get/set 方法对应的属性
  propertyutilsbean propertyutilsbean = new propertyutilsbean();
  propertydescriptor[] descriptors = propertyutilsbean.getpropertydescriptors(src);

  for (int i = 0; i < descriptors.length; i++) {
   propertydescriptor propitem = descriptors[i];
   // 过滤setclass/getclass属性
   if ("class".equals(propitem.getname())) {
    continue;
   }

   try {
    method method = propitem.getreadmethod();
    // 通过get方法获取对应的值
    object val = method.invoke(src);
    // 如果是空,不做处理
    if (null == val) {
     continue;
    }
    if(val instanceof string) {
     if(stringutils.isblank(val.tostring())) {
      continue;
     }
    }
    // 值复制
    propertydescriptor prop = propertyutilsbean.getpropertydescriptor(dest, propitem.getname());
    // 调用写方法,设置值
    if (null != prop && prop.getwritemethod() != null) {
     prop.getwritemethod().invoke(dest, val);
    }
   } catch (exception e) {
   }

  }

 }
 
 public static <t> t maptoentity(map<string, object> map, class<t> entity) {
  t t = null;
  try {
   t = entity.newinstance();
   for(field field : entity.getdeclaredfields()) {
    if (map.containskey(field.getname())) {
     boolean flag = field.isaccessible();
              field.setaccessible(true);
              object object = map.get(field.getname());
              if (object!= null && field.gettype().isassignablefrom(object.getclass())) {
                field.set(t, object);
     }
              field.setaccessible(flag);
    }
   }
   return t;
  } catch (instantiationexception e) {
   e.printstacktrace();
  } catch (illegalaccessexception e) {
   e.printstacktrace();
  }
  return t;

 } 

}

拦截器appinterceptor.java

package com.jx.app.api.framework.interceptor;

import java.util.map;

import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;

import org.apache.commons.lang3.stringutils;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.web.method.handlermethod;
import org.springframework.web.servlet.handlerinterceptor;

import com.google.gson.gson;
import com.jx.app.api.framework.annotation.loginanot;
import com.jx.app.api.framework.annotation.sginanot;
import com.jx.app.api.framework.annotation.enums.auth;
import com.jx.app.api.framework.annotation.enums.sginenum;
import com.jx.common.entrypt.md5;
import com.jx.common.entrypt.sha1;
import com.jx.common.token.serviceexception;
import com.jx.common.token.tokenexception;
import com.jx.common.token.tokenutil;
import com.jx.common.utils.constants;
import com.jx.common.utils.requestutil;
import com.jx.common.utils.result;
import com.jx.common.utils.enums.codeenum;
import com.jx.core.api.model.basemodel;

/**  
* @classname: appinterceptor  
* @description: todo(拦截器)  
* @author gangyu
* @date 2018年11月20日 下午4:10:55  
*    
*/
public class appinterceptor implements handlerinterceptor{
    private final static logger logger = loggerfactory.getlogger(appinterceptor.class);
 
 private static final string content_type="text/json;charset=utf-8";
 
 @override
 public boolean prehandle(httpservletrequest request, httpservletresponse response, object handler)
   throws exception {
    if (handler.getclass().isassignablefrom(handlermethod.class)) {
      //签名验证注解
          sginanot signanot = ((handlermethod) handler).getmethodannotation(sginanot.class);
          
          //验签
          if(signanot!=null && !signcheck(request,signanot.type())){
              response.setcontenttype(content_type);
                 response.getwriter().print(new gson().tojson(new result(codeenum.sign_fail)));
                 return false;
          }
    return true;
    }else{
    return true;
    }
 }

 private boolean signcheck(httpservletrequest request,sginenum enumm){
  map<string,object> map=requestutil.parserequset(request);
  if(enumm==sginenum.md5){
   return md5.check(map);
  }else if(enumm==sginenum.sha1){
   return sha1.check(map);
  }
  return false;
 }
 }
 }
}

统一返回对象result.java

package com.jx.common.utils;


import java.io.serializable;

import com.google.gson.gson;
import com.jx.common.entrypt.des;
import com.jx.common.utils.enums.codeenum;

/**
 * 结果dto
 * @lastmodified
 * @history
 */

public class result implements serializable{
 private static final long serialversionuid = 1l;

 /**
  * 结果详细
  */
 private string msg;

 /**
  * 需要传回页面的数据
  */
 private object data;
 
 /**
  * 状态码
  */
 private string code;
 
 /**
  * 加密
  */
 private boolean encrypt;
 
 /**
  * 图标
  */
 private integer icon;

 public boolean isencrypt() {
  return encrypt;
 }

 public void setencrypt(boolean encrypt) {
  this.encrypt = encrypt;
 }

 public string getmsg() {
  return msg;
 }

 public void setmsg(string msg) {
  this.msg = msg;
 }

 public result() {

 }

 public result(codeenum enums) {
  this.msg = enums.getmsg();
  this.encrypt = enums.getencrypt();
  this.code = enums.getcode();
  this.icon = enums.geticon();
 }

 public result(codeenum enums,object data) {
  this.msg = enums.getmsg();
  this.encrypt = enums.getencrypt();
  this.code = enums.getcode();
  this.icon=enums.geticon();
  if(enums.getencrypt()){
   this.data=des.encode(new gson().tojson(data));
  }else{
   this.data=data;
  }
 }

 public object getdata() {
  return data;
 }

 public void setdata(object data) {
  this.data = data;
 }


 public string getcode() {
  return code;
 }

 public void setcode(string code) {
  this.code = code;
 }

 public integer geticon() {
  return icon;
 }

 public void seticon(integer icon) {
  this.icon = icon;
 }

 public static result success(codeenum enums) {
  result dto = new result();
  dto.setmsg(enums.getmsg());
  dto.setencrypt(enums.getencrypt());
  dto.setcode(enums.getcode());
  dto.seticon(enums.geticon());
  return dto;
 }
 
 public static result success(codeenum enums,object data) {
  result dto = new result();
  dto.setdata(data);
  dto.setencrypt(enums.getencrypt());
  dto.setcode(enums.getcode());
  dto.seticon(enums.geticon());
  if(enums.getencrypt()){
   dto.setdata(des.encode(new gson().tojson(data)));
  }else{
   dto.setdata(data);
  }
  return dto;
 }
 
 public static result fail(string msg) {
  result dto = new result();
  dto.setmsg(msg);
  dto.setencrypt(false);
  dto.setcode("1");
  dto.seticon(syscode.icon.icon_fail);
  return dto;
 }
}

状态码枚举类codeenum.java

package com.jx.common.utils.enums;
/**  
* @classname: exceptionenum  
* @description: todo(系统编码)  
* @author gangyu
* @date 2018年11月21日 下午5:22:32  
*/
public enum codeenum {
 //系统编码
    sys_exception("999",false,"系统异常",'fail'),
    success("0",false,"成功",'success'),
    encrypt("0",true,"成功",'success'),
    fail("1",false,"失败",'fail'),
    sign_fail("1",false,"签名不正确",'fail'),
    data_empty("0",false,"暂无数据",'success'),
    ;

    private string code;
    
    private string msg;
    
    private boolean encrypt;
    
    private integer icon;

    codeenum(string code,boolean encrypt, string msg,integer icon) {
        this.code = code;
        this.encrypt = encrypt;
        this.msg = msg;
        this.icon = icon;
    }

    public integer geticon() {
  return icon;
 }

 public string getcode() {
        return code;
    }

    public string getmsg() {
        return msg;
    }

 public boolean getencrypt() {
  return encrypt;
 }    
}

controller层使用签名注解

 @requestmapping(value="encryptentity",produces = "application/json;charset=utf-8",method=requestmethod.post)
    @sginanot(type = sginenum.md5)
    public  object encryptentity(testentity test){
        return businessservice.encryptentity(test);
    }
  • 验签加密排序根据asii表进行排序在beanutil.java类里已经实现
  • url?a=1&c=2&b=3。。。->排序后 a=1&b=3&c=2 然后进行数据加密 俩边排序方式要一致当然为了安全可以排完序加入自己的密钥在进行一次加密
  • result.java提供了返回数据加密方法codeenum.encrypt这里使用的是des对称加密

到此这篇关于springboot自定义注解api数据加密和签名校验的文章就介绍到这了,更多相关springboot 数据加密和签名校验内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!