一、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(); } }
测试: