美文网首页
请求参数加密,在过滤filter中处理参数

请求参数加密,在过滤filter中处理参数

作者: pretty_rain | 来源:发表于2019-05-23 15:33 被阅读0次

参数格式说明:1.reqmsg=业务数据 2.sign=MD5数字签名

参数 内容 加密解密方式 格式
reqmsg 所有业务数据 整个明文内容(包括JSON符号)先进行UTF-8编码,再DES加密,然后BASE64编码 普通字符串
sign 所有业务数据 先UTF-8编码,再MD5加密,然后BASE64编码 普通字符串

接口实现思路:配置springboot过滤器然后在写一个自定义的MyRequestWrapper 类继承HttpServletRequestWrapper 重写三个方法getParameterNames、getParameter、getParameterValues

1.过滤器代码
@Component
@Order
@WebFilter(urlPatterns = "/*", filterName = "requestParamFilter")
public class RequestParamFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest)servletRequest;
        HttpServletResponse rsp = (HttpServletResponse)servletResponse;
        /**
         * 自定义request类
         */
        MyRequestWrapper myReq = new MyRequestWrapper(req);
        filterChain.doFilter(myReq,rsp);
        //filterChain.doFilter(req,rsp);
    }
   @Override
    public void destroy() {
    }
}
2.自定义request类
public class MyRequestWrapper extends HttpServletRequestWrapper{

    private HttpServletRequest request;

    //将request对象中的参数修改后,放在这个集合里,随后项目取的所有Parameter都是从这个集合中取数
    private Set<String> keySet = new HashSet();

    //所有业务数据的全部明文内容(包括json符号)的MD5数字签名
    private String sign;

    public MyRequestWrapper(HttpServletRequest request) {
        super(request);
        this.request = request;

        //先通过request原生的方法,遍历获取到的参数
        Enumeration enu = request.getParameterNames();
        while (enu.hasMoreElements()) {
            String paraName = (String) enu.nextElement();
            try {
                if ("reqmsg".equals(paraName)) {
                    String decrypt = DesUtil.decrypt(request.getParameter(paraName).toString().replace(" ","+"));
                    if (JSONUtil.isJsonObject(decrypt)) {
                        JSONObject jsonObject = JSON.parseObject(decrypt);
                        keySet = JSONUtil.getAllKeys(jsonObject.toJSONString());
                    }
                }
                keySet.add(paraName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(request.getParameter("sign") != null){
            sign = request.getParameter("sign");
        }
    }

    /**
     * 获取所有参数
     *
     * @return
     */
    @Override
    public Enumeration<String> getParameterNames() {

        Vector<String> v = new Vector<String>();
        for (String key : keySet) {
            v.add(key);
        }
        Enumeration<String> en = v.elements();
        return en;
    }

    /**
     * 重写了父类的 getParameter 方法
     *
     * @param name
     * @return
     */
    @Override
    public String getParameter(String name) {

        if (StringUtils.isNotBlank(name)) {
            if (request.getParameter("reqmsg") != null) {
                String reqmsg = request.getParameter("reqmsg").toString();
                try {
                    String decrypt = DesUtil.decrypt(reqmsg);
                    if (JSONUtil.isJsonObject(decrypt) && sign.equals(Base64.getEncoder().encodeToString(MD5Util.md5(decrypt,null)))) {
                        JSONObject jsonObject = JSON.parseObject(decrypt);
                        if (jsonObject.containsKey(name)) return jsonObject.getString(name);
                        return request.getParameter(name);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return request.getParameter(name);
        }
        return null;
    }

    /**
     * 重写了父类的 getParameterValues 方法
     *
     * @param name
     * @return
     */
    @Override
    public String[] getParameterValues(String name) {

        if (StringUtils.isNotBlank(name)) {
            if (request.getParameter("reqmsg") != null) {
                String reqmsg = request.getParameter("reqmsg").toString();
                try {
                    String decrypt = DesUtil.decrypt(reqmsg);
                    JSONObject jsonObject = JSON.parseObject(decrypt);
                    if (jsonObject.containsKey(name)  && sign.equals(Base64.getEncoder().encodeToString(MD5Util.md5(decrypt,null)))) {
                        String value = jsonObject.getString(name);
                        //判断是否是json数组
                        if (JSONUtil.isJsonArray(value)) {

                            JSONArray jsonArray = JSONArray.parseArray(value);
                            return (String[]) jsonArray.toArray();
                        }
                        return StringUtils.isNotBlank(value) ? new String[]{value} :  new String[]{};
                    }
                    return request.getParameterValues(name);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return request.getParameterValues(name);
        }
        return null;
    }
}
3.用到的DES解密工具类
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;

/**
 * 解密请求参数
 * Created by Administrator on 2019/5/21.
 */
public class DesUtil {

    /**
     * 加密解密方式
     */
    private final static String DES = "DES";
    /**
     * 秘钥
     */
    private final static String DEFAULTKEY = "mOAmKLeRIFz15XOTE1PWjg==";
    /**
     * 字符编码
     */
    private final static String ENCODE = "UTF-8";
    /**
     * 解码
     */
    private final static Base64.Decoder DECODER = Base64.getDecoder();
    /**
     * 编码
     */
    private final static Base64.Encoder ENCODER = Base64.getEncoder();
    
    /**
     * 加密
     * @param data
     * @return
     * @throws Exception
     */
    public static String encrypt(String data) throws Exception {
        byte[] bt = encrypt(data.getBytes(ENCODE), DEFAULTKEY.getBytes(ENCODE));
        String strs = ENCODER.encodeToString(bt);
        return strs;
    }

    private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
        // 生成一个可信任的随机数源
        SecureRandom sr = new SecureRandom();

        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);

        // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);

        // Cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance(DES);

        // 用密钥初始化Cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);

        return cipher.doFinal(data);
    }

    /**
     * 解密
     * @param data
     * @return
     * @throws IOException
     * @throws Exception
     */
    public static String decrypt(String data) throws IOException, Exception {
        if (data == null)
            return null;

        byte[] buf = DECODER.decode(data);
        byte[] bt = decrypt(buf, DEFAULTKEY.getBytes(ENCODE));
        return new String(bt, ENCODE);
    }

    private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        // 生成一个可信任的随机数源
        SecureRandom sr = new SecureRandom();

        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);

        // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);

        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance(DES);

        // 用密钥初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, securekey, sr);

        return cipher.doFinal(data);
    }


    public static void main(String[] args) throws Exception {
        String data = "{\"districtId\":\"412\",\"size\":\"6\"}";
        // System.err.println(encrypt(data, key));
        // System.err.println(decrypt(encrypt(data, key), key));
        System.out.println(encrypt(data));
        System.out.println(decrypt(encrypt(data)));


    }
}
4.用的JSON工具类
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * Created by Administrator on 2019/5/23.
 */
public class JSONUtil {


    /**
     * bean对象转json字符串
     *
     * @param obj
     * @param dataFormatString
     * @return
     */
    public static String beanToJson(Object obj, String dataFormatString) {
        if (obj != null) {
            if (StringUtils.isEmpty(dataFormatString)) {
                return JSONObject.toJSONString(obj);
            }
            return JSONObject.toJSONStringWithDateFormat(obj, dataFormatString);
        }
        return null;
    }

    /**
     * bean对象转json字符串
     *
     * @param obj
     * @return
     */
    public static String beanToJson(Object obj) {
        if (obj != null) {
            return JSONObject.toJSONString(obj);
        }
        return null;
    }

    /**
     * string字符串转成json字符串
     *
     * @param key
     * @param value
     * @return
     */
    public static String stringToJonByFastjson(String key, String value) {
        if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
            return null;
        }
        Map<String, String> map = new HashMap<>();
        map.put(key, value);
        return beanToJson(map);
    }

    /**
     * json字符串转bean对象
     *
     * @param json
     * @param clazz
     * @return
     */
    public static Object stringToBean(String json, Object clazz) {
        if (StringUtils.isEmpty(json) || clazz == null) {
            return null;
        }
        return JSONObject.parseObject(json, clazz.getClass());
    }

    /**
     * json字符串转换成map对象
     *
     * @param json
     * @return
     */
    public static Map<String, Object> jsonToMap(String json) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        return JSONObject.parseObject(json, Map.class);
    }


    /**
     * 判断字符串是否可以转化为JSON数组
     *
     * @param content
     * @return
     */
    public static boolean isJsonArray(String content) {
        if (StringUtils.isEmpty(content))
            return false;
        StringUtils.isEmpty(content);
        try {
            JSONArray jsonStr = JSONArray.parseArray(content);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 判断字符串是否可以转化为json对象
     *
     * @param content
     * @return
     */
    public static boolean isJsonObject(String content) {
        if (StringUtils.isEmpty(content))
            return false;
        try {
            JSONObject jsonStr = JSONObject.parseObject(content);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取json字符串中所有的key值
     *
     * @param jsonString
     * @return
     */
    public static Set<String> getAllKeys(String jsonString) {
        Set<String> set = new HashSet<>();
        //按照","将json字符串分割成String数组
        String[] keyValue = jsonString.split(",");
        for (int i = 0; i < keyValue.length; i++) {
            String s = keyValue[i];
            //找到":"所在的位置,然后截取
            int index = s.indexOf(":");
            if (index == -1) {
                return set;
            }
            //第一个字符串因带有json的"{",需要特殊处理
            if (i == 0) {
                set.add(s.substring(2, index - 1));
            } else {
                set.add(s.substring(1, index - 1));
            }
        }
        return set;
    }
}

相关文章

网友评论

      本文标题:请求参数加密,在过滤filter中处理参数

      本文链接:https://www.haomeiwen.com/subject/kjxbzqtx.html