springboot中使用filter實現body參數解密,header版本效驗

springboot配置filter過濾器:

        1.創建filter類:

               


import com.hpm.blog.model.Appapk;
import com.hpm.blog.service.AppapkService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

public class KevinTokenFilter implements Filter {

    private FilterConfig config;
    private AppapkService appapkService;


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        config = filterConfig;
        /**
         * 注入AppapkService對象  用戶查詢數據庫

         */
        ServletContext sc = filterConfig.getServletContext();

        WebApplicationContext cxt = WebApplicationContextUtils.getWebApplicationContext(sc);

        if (cxt != null && cxt.getBean(AppapkService.class) != null && appapkService == null) {

            appapkService = (AppapkService) cxt.getBean(AppapkService.class);
        }
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //如果這是個http請求
        if(request instanceof HttpServletRequest) {
          //強轉成http請求
          HttpServletRequest req1 = (HttpServletRequest) request;
            //3.創建LogHttpServletRequestWrapper類繼承HttpServletRequestWrapper,並且將http請求 req1放入到創建的LogHttpServletRequestWrapper類中。並且在此類中做解密操作。
            LogHttpServletRequestWrapper req = new LogHttpServletRequestWrapper(req1);
            Map<String, Object> parameterMap=new LinkedHashMap<>();
            String apk = req.getHeader("user-agent");//取出header中的版本信息
            int num = apk.indexOf("_");
            String apktype = apk.substring(0,num);
            String edition = apk.substring(num+1,apk.length());
            Appapk appapk = appapkService.queryAppapkbyheader(edition,apktype);
            //判斷版本信息是否放行
            if (null != appapk) {
                /*if("GET".equals(req.getMethod())){
                    parameterMap= JSONUtil.parseObj(ServletUtil.getParams(request));
                }else{
                    parameterMap= JSONUtil.parseObj(req.getBody());
                }*/
                //放行訪問
                chain.doFilter(req, response);
            } else {
                //否則默認訪問index接口
//                wrapper.sendRedirect("https://www.baidu.com");
                req.getRequestDispatcher("/index").forward(request,response);
            }
        }

//        chain.doFilter(request, response);

//    HttpServletRequest request, HttpServletResponse response
    }

    @Override
    public void destroy() {

    }
}

2.將filter對象放入對象池中:


import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class WebComponent2Config {
    @Bean
    public FilterRegistrationBean someFilterRegistration1() {
        //新建過濾器註冊類
        FilterRegistrationBean registration = new FilterRegistrationBean();
        // 添加我們寫好的過濾器
        registration.setFilter( new KevinTokenFilter());
        // 設置過濾器的URL模式
        registration.addUrlPatterns("/*");
        return registration;
    }
}

  3. //創建LogHttpServletRequestWrapper類繼承HttpServletRequestWrapper


import com.hpm.blog.util.RSAEncrypt;
import net.sf.json.JSONObject;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;

public class LogHttpServletRequestWrapper extends HttpServletRequestWrapper {
    private final String body;

    public LogHttpServletRequestWrapper(HttpServletRequest request){
        super(request);
        //創建字符緩衝區
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        InputStream inputStream = null;
        try {
            inputStream = request.getInputStream();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                //將輸入流裏面的參數讀取到字符緩衝區
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            } else {
                stringBuilder.append("");
            }
        } catch (IOException ex) {

        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //s爲接口請求參數字符串類型
        String s = stringBuilder.toString();
        if(!"".equals(s)){
            開始解密字符串類型參數
            JSONObject json = RSAEncrypt.decryptJson( JSONObject.fromObject(stringBuilder.toString()));
            body = json.toString();
        }else{
            body=s;
        }
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
        ServletInputStream servletInputStream = new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }
            @Override
            public boolean isReady() {
                return false;
            }
            @Override
            public void setReadListener(ReadListener readListener) {
            }
            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }
        };
        return servletInputStream;

    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

    public String getBody() {
        return this.body;
    }

}

關於參數加密、解密、生成RSA祕鑰的方法:


import com.hpm.blog.model.ReturnResult;
import com.hpm.blog.util.Constants;
import com.hpm.blog.util.RSAEncrypt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class RsamessageApi {

    @RequestMapping("/shengchengmiyao")
    public ReturnResult generatersakey(@RequestBody Map<String, String> map) throws Exception {
        String message = String.valueOf(map.get("message"));
        ReturnResult result = new ReturnResult();
        Map keyMap = RSAEncrypt.genKeyPair();
        //加密字符串
//        String message = "maojungang";
        System.out.println("隨機生成的公鑰爲:" + keyMap.get(0));
        System.out.println("隨機生成的私鑰爲:" + keyMap.get(1));
        String messageEn = RSAEncrypt.encrypt(message,(String)keyMap.get(0));
        System.out.println(message + "\t加密後的字符串爲:" + messageEn);
        String messageDe = RSAEncrypt.decrypt(messageEn,(String)keyMap.get(1));
        System.out.println("還原後的字符串爲:" + messageDe);
        Map Maps = new HashMap();
        Maps.put("隨機公鑰",keyMap.get(0));
        Maps.put("隨機私鑰",keyMap.get(1));
        Maps.put("加密字符串","maojungang");
        Maps.put("加密後字符串",messageEn);
        Maps.put("解密後字符串",messageDe);
        result.setData(Maps);
        result.setCode("10000");
        result.setMessage("查詢成功");
        return result;
    }
    @RequestMapping(value = "/jiemi",method = RequestMethod.POST)
    public ReturnResult testrsakey(@RequestBody Map<String, String> map) throws Exception {
        String messageEn = String.valueOf(map.get("message"));
        ReturnResult result = new ReturnResult();
 //       Map keyMap = RSAEncrypt.genKeyPair();

        //加密字符串
//        String message = "maojungang";
        /*System.out.println("隨機生成的公鑰爲:" + keyMap.get(0));
        System.out.println("隨機生成的私鑰爲:" + keyMap.get(1));
        String messageEn = RSAEncrypt.encrypt(message,(String)keyMap.get(0));
        System.out.println(message + "\t加密後的字符串爲:" + messageEn);*/
        //Constants.RSAPRIVITEKEY是用上面方法生成的私鑰,用解密密文字符串
        String messageDe = RSAEncrypt.decrypt(messageEn, Constants.RSAPRIVITEKEY);
        System.out.println("還原後的字符串爲:" + messageDe);
        Map Maps = new HashMap();
        Maps.put("加密後字符串",messageEn);
        Maps.put("解密後字符串",messageDe);
        result.setData(Maps);
        result.setCode("10000");
        result.setMessage("查詢成功");
        return result;
    }
    @RequestMapping(value = "/jiami",method = RequestMethod.POST)
    public ReturnResult jiamikey(@RequestBody Map<String, String> map) throws Exception {
        String message = String.valueOf(map.get("message"));
        ReturnResult result = new ReturnResult();
        //Constants.PUBLICKEY是用上面方法生成的公鑰,用於前端加密字符串生成密文
        String messageEn = RSAEncrypt.encrypt(message,Constants.PUBLICKEY);
        System.out.println(message + "\t加密後的字符串爲:" + messageEn);
        Map Maps = new HashMap();
        Maps.put("加密後字符串",messageEn);
        result.setData(Maps);
        result.setCode("10000");
        result.setMessage("查詢成功");
        return result;
    }
}

參數解密封裝的工具類:


import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;


public class RSAEncrypt {

    private static Map<Integer, String> keyMap = new HashMap<Integer, String>();  //用於封裝隨機產生的公鑰與私鑰

    /**
     * 隨機生成密鑰對
     * @throws NoSuchAlgorithmException
     */
    public static Map genKeyPair() throws NoSuchAlgorithmException {
        // KeyPairGenerator類用於生成公鑰和私鑰對,基於RSA算法生成對象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        // 初始化密鑰對生成器,密鑰大小爲96-1024位
        keyPairGen.initialize(1024,new SecureRandom());
        // 生成一個密鑰對,保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私鑰
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公鑰
        String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
        // 得到私鑰字符串
        String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
        // 將公鑰和私鑰保存到Map
        keyMap.put(0,publicKeyString);  //0表示公鑰
        keyMap.put(1,privateKeyString);  //1表示私鑰
        return keyMap;
    }
    /**
     * RSA公鑰加密
     *
     * @param str
     *            加密字符串
     * @param publicKey
     *            公鑰
     * @return 密文
     * @throws Exception
     *             加密過程中的異常信息
     */
    public static String encrypt( String str, String publicKey ) throws Exception{
        //base64編碼的公鑰
        byte[] decoded = Base64.decodeBase64(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
        return outStr;
    }

    /**
     * RSA私鑰解密
     *
     * @param str
     *            加密字符串
     * @param privateKey
     *            私鑰
     * @return 銘文
     * @throws Exception
     *             解密過程中的異常信息
     */
    public static String decrypt(String str, String privateKey) throws Exception{
        //64位解碼加密後的字符串
        byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
        //base64編碼的私鑰
        byte[] decoded = Base64.decodeBase64(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        String outStr = new String(cipher.doFinal(inputByte));
        return outStr;
    }

    public static Map<String, Object> decryptMap(Map<String, Object> map){
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            entry.setValue(fordecrypt(String.valueOf(entry.getValue())));
        }
        return map;
    }
    public static JSONObject decryptJson(JSONObject jsonObject){
        Map<String, Object> map = new HashMap<String, Object>();
        map.putAll(jsonObject);
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            entry.setValue(fordecrypt(String.valueOf(entry.getValue())));
        }
        JSONObject json = JSONObject.fromObject(map);
        return json;
    }
    public static String fordecrypt(String str){
        String outStr = "";
        try{
            //64位解碼加密後的字符串
            byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
            //base64編碼的私鑰
            byte[] decoded = Base64.decodeBase64(Constants.RSAPRIVITEKEY);
            RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
            //RSA解密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            outStr = new String(cipher.doFinal(inputByte));
        }catch (Exception e){

        }

        return outStr;
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章