springboot整合RSA驗簽功能-提供API接口


一、RSA工具類

RSAUtil 里面包含了加密解密,加簽驗簽方法,參數用treemap排序

package com.zhouzy.boot.zhouzyBoot.config;

import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.alibaba.fastjson.JSONObject;
 
/**
 * Created by 李嘯天 on 2019/3/13.
 */
public class RSAUtil {
    public static final String KEY_ALGORITHM = "RSA";
    public static final String PUBLIC_KEY = "RSAPublicKey";
    public static final String PRIVATE_KEY = "RSAPrivateKey";
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
    
    public static String publicKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKzScQr1M6hWWiwNzwraVFoMxxHrGLR3Xr144hUOGCg46IkaSrriVL5BACQJ5Z1P43k+McshEpkOKSpOXFcJkNkCAwEAAQ==";
    public static String privateKey = "MIIBVgIBADANBgkqhkiG9w0BAQEFAASCAUAwggE8AgEAAkEArNJxCvUzqFZaLA3PCtpUWgzHEesYtHdevXjiFQ4YKDjoiRpKuuJUvkEAJAnlnU/jeT4xyyESmQ4pKk5cVwmQ2QIDAQABAkEAjFo7xBJu6X93q99rDf1SE+/cnAi5/5YSMv5BXagcpkx60ImxPRGG0NIeMb0WxShbT/5J7kJzW7ufceg20BFCoQIhAOGddY8sFiU/Nyhyt+37CnzQ2a+vCimvpUL4A1BWqOnjAiEAxBjVoXme9EQVlVYl3joc60EbiwPTpBTvLNsGUfRpBxMCIQCB7do735nJTYSIaLh/9ujtRKF4yYdCxoKX9JiD9cRFHQIhAIR8mukr+H7j+QkaWR9Zd+xh4q/7d+Ql2KofmJeKX+NNAiBcXRtcvtsIeIWTTFwMFBhaO8y0CEAXJ0JJBSDLU+SRaQ==";
    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;
 
    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 2048;
 
    //獲得公鑰字符串
    public static String getPublicKeyStr(Map<String, Object> keyMap) throws Exception {
        //獲得map中的公鑰對象 轉為key對象
        Key key = (Key) keyMap.get(PUBLIC_KEY);
        //編碼返回字符串
        return encryptBASE64(key.getEncoded());
    }
 
 
    //獲得私鑰字符串
    public static String getPrivateKeyStr(Map<String, Object> keyMap) throws Exception {
        //獲得map中的私鑰對象 轉為key對象
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        //編碼返回字符串
        return encryptBASE64(key.getEncoded());
    }
 
    //獲取公鑰
    public static PublicKey getPublicKey(String key) throws Exception {
        byte[] keyBytes;
        keyBytes = (new BASE64Decoder()).decodeBuffer(key);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }
 
    //獲取私鑰
    public static PrivateKey getPrivateKey(String key) throws Exception {
        byte[] keyBytes;
        keyBytes = (new BASE64Decoder()).decodeBuffer(key);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }
 
    //解碼返回byte
    public static byte[] decryptBASE64(String key) throws Exception {
        return (new BASE64Decoder()).decodeBuffer(key);
    }
 
 
    //編碼返回字符串
    public static String encryptBASE64(byte[] key) throws Exception {
        return (new BASE64Encoder()).encodeBuffer(key);
    }
 
    //***************************簽名和驗證*******************************
    public static byte[] sign(byte[] data, String privateKeyStr) throws Exception {
        PrivateKey priK = getPrivateKey(privateKeyStr);
        Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
        sig.initSign(priK);
        sig.update(data);
        return sig.sign();
    }
 
    public static boolean verify(byte[] data, byte[] sign, String publicKeyStr) throws Exception {
        PublicKey pubK = getPublicKey(publicKeyStr);
        Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
        sig.initVerify(pubK);
        sig.update(data);
        return sig.verify(sign);
    }
 
    //************************加密解密**************************
    public static byte[] encrypt(byte[] plainText, String publicKeyStr) throws Exception {
        PublicKey publicKey = getPublicKey(publicKeyStr);
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        int inputLen = plainText.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        int i = 0;
        byte[] cache;
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(plainText, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(plainText, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptText = out.toByteArray();
        out.close();
        return encryptText;
    }
 
    public static byte[] decrypt(byte[] encryptText, String privateKeyStr) throws Exception {
        PrivateKey privateKey = getPrivateKey(privateKeyStr);
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        int inputLen = encryptText.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 對數據分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptText, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptText, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] plainText = out.toByteArray();
        out.close();
        return plainText;
    }
 
 
    public static void main(String[] args) {
        Map<String, Object> keyMap;
        byte[] cipherText;
        String input = "Hello World!";
        try {
            keyMap = initKey();
            //String publicKey = getPublicKeyStr(keyMap);
            System.out.println("公鑰------------------");
            System.out.println(publicKey);
            //String privateKey = getPrivateKeyStr(keyMap);
            System.out.println("私鑰------------------");
            System.out.println(privateKey);
 
            System.out.println("測試可行性-------------------");
            System.out.println("明文=======" + input);
 
            cipherText = encrypt(input.getBytes(), publicKey);
            //加密后的東西
            System.out.println("密文=======" + new String(cipherText));
            //開始解密
            byte[] plainText = decrypt(cipherText, privateKey);
            System.out.println("解密后明文===== " + new String(plainText));
            System.out.println("驗證簽名-----------");
 
            TreeMap map = new TreeMap(new MComparator());  
            map.put("age", 20);
            map.put("name", "張三");
            String str = JSONObject.toJSONString(map);
            System.out.println("\n原文:" + str);
            byte[] signature = sign(str.getBytes(), privateKey);
            System.out.println(Base64.encodeBase64String(signature));
            boolean status = verify(str.getBytes(), signature, publicKey);
            System.out.println("驗證情況:" + status);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Map<String, Object> initKey() throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator
                .getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(1024);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        Map<String, Object> keyMap = new HashMap<String, Object>(2);
        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;
    }
    
   static class MComparator implements Comparator {  
        public int compare(Object obj1, Object obj2) {  
            String ele1 = (String) obj1;  
            String ele2 = (String) obj2;  
            return ele2.compareTo(ele1);  
        } 
    }
 
}

Base64Util 主要用於傳輸內容加解密用

package com.zhouzy.boot.zhouzyBoot.config;

import org.apache.commons.codec.binary.Base64;

/**
 * Base64
 * Author:Bobby
 * DateTime:2019/4/9
 **/
public class Base64Util{

    /**
     * Decoding to binary
     * @param base64 base64
     * @return byte
     * @throws Exception Exception
     */
    public static byte[] decode(String base64) throws Exception {
        return Base64.decodeBase64(base64);
    }

    /**
     * Binary encoding as a string
     * @param bytes byte
     * @return String
     * @throws Exception Exception
     */
    public static String encode(byte[] bytes) throws Exception {
        return new String(Base64.encodeBase64(bytes));
    }
}

攔截器InterceptorConfig,在這里實現參數的驗簽功能

package com.zhouzy.boot.zhouzyBoot.config;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhouzy.boot.zhouzyBoot.config.RSAUtil.MComparator;
 
@Component
public class InterceptorConfig implements HandlerInterceptor {
    private static Logger logger = LoggerFactory.getLogger(InterceptorConfig.class);
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //獲取請求參數
        String queryString = httpServletRequest.getQueryString();
        logger.info("請求參數:{}", queryString);
 
        //獲取請求body
        byte[] bodyBytes = StreamUtils.copyToByteArray(httpServletRequest.getInputStream());
        String body = new String(bodyBytes, httpServletRequest.getCharacterEncoding());
        logger.info("請求體:{}", body);
        Map<String, Object> map = JSON.parseObject(body,Map.class);
        String signStr = String.valueOf(map.get("sign"));
        byte[] sign = org.apache.commons.codec.binary.Base64.decodeBase64(signStr);
        map.remove("sign");
        Set set = map.keySet();
        Iterator it = set.iterator();
        TreeMap tm = new TreeMap(new MComparator());  
        while(it.hasNext()){
            String key = String.valueOf(it.next());
            tm.put(key, map.get(key));
        }
        
        Map<String, Object> keyMap = RSAUtil.initKey();
        String publicKey = RSAUtil.publicKey;
        String mapSortStr = JSONObject.toJSONString(tm);
        logger.info("傳過來的字符串:mapSortStr:{}",mapSortStr);
//        //公鑰驗證
        boolean flagB = RSAUtil.verify(mapSortStr.getBytes(),sign,publicKey);
        if(flagB){
            return true;
        }else {
            return false;
        }
    }
 
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        logger.info("兌換服務攔截器-處理請求完成后視圖渲染之前的處理操作");
    }
 
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        logger.info("兌換服務攔截器-視圖渲染之后的操作");
    }
}

AxinHttpServletRequestWrapper這個主要是包裝HttpServletRequest,因為HttpServletRequest只能讀一次流,所以需要一個包裝類,否則controller類接收不到參數

package com.zhouzy.boot.zhouzyBoot.config;

import org.springframework.util.StreamUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
 
/**
 * @author Axin
 * @summary 自定義 HttpServletRequestWrapper 來包裝輸入流
 */
public class AxinHttpServletRequestWrapper extends HttpServletRequestWrapper {
 
    /**
     * 緩存下來的HTTP body
     */
    private byte[] body;
 
    public AxinHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        body = StreamUtils.copyToByteArray(request.getInputStream());
    }
 
    /**
     * 重新包裝輸入流
     * @return
     * @throws IOException
     */
    @Override
    public ServletInputStream getInputStream() throws IOException {
        final InputStream bodyStream = new ByteArrayInputStream(body);
        return new ServletInputStream() {
 
            @Override
            public int read() throws IOException {
                return bodyStream.read();
            }
 
            /**
             * 下面的方法一般情況下不會被使用,如果你引入了一些需要使用ServletInputStream的外部組件,可以重點關注一下。
             * @return
             */
            @Override
            public boolean isFinished() {
                return false;
            }
 
            @Override
            public boolean isReady() {
                return true;
            }
 
            @Override
            public void setReadListener(ReadListener readListener) {
 
            }
        };
    }
 
    @Override
    public BufferedReader getReader() throws IOException {
        InputStream bodyStream = new ByteArrayInputStream(body);
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }
}

AxinDispatcherServlet  自定義 DispatcherServlet 來分派 AxinHttpServletRequestWrapper

package com.zhouzy.boot.zhouzyBoot.config;

import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * @author Axin
 * @summary 自定義 DispatcherServlet 來分派 AxinHttpServletRequestWrapper
 */
public class AxinDispatcherServlet extends DispatcherServlet {
 
    /**
     * 包裝成我們自定義的request
     * @param request
     * @param response
     * @throws Exception
     */
    @Override
    protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
        super.doDispatch(new AxinHttpServletRequestWrapper(request), response);
    }
}

ApiController測試接口類

package com.zhouzy.boot.zhouzyBoot.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

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 com.alibaba.fastjson.JSONObject;
import com.zhouzy.boot.zhouzyBoot.model.User;

@RestController
public class ApiController {
     private static Logger logger = LoggerFactory.getLogger(ApiController.class);

     @RequestMapping(value = "/api/testSign",method =RequestMethod.POST)
    public void testSign(@RequestBody User user,HttpServletRequest request){
         
        logger.info(JSONObject.toJSONString(user));
    }
}

WebApplication啟動類

package com.zhouzy.boot.zhouzyBoot;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.DispatcherServlet;

import com.zhouzy.boot.zhouzyBoot.config.AxinDispatcherServlet;


@EnableAutoConfiguration
@SpringBootApplication
class WebApplication{
    public static void main(String[] args) {
        SpringApplication.run(WebApplication.class, args);
    }
    
     @Bean(name="remoteRestTemplate")
     public RestTemplate restTemplate() {
            return new RestTemplate();
     }
     
     @Bean
        @Qualifier(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
        public DispatcherServlet dispatcherServlet() {
            return new AxinDispatcherServlet();
        }
}

測試:

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM